친숙한 URL을위한 안전한 문자
기사가있는 웹 사이트를 만들어야하며, URL이 포함 된 페이지의 URL과 같이 친숙한 URL을 만들고 싶습니다.
제목 : 기사 테스트
되어야합니다 : http://www.example.com/articles/article_test
.
물론 내가 좋아하는 제목에서 일부 문자를 제거해야 ?
하거나 #
,하지만 확실히 제거 할 것 아니에요.
어떤 캐릭터가 보관하기에 안전한지 말해 줄 수 있습니까?
RFC 3986의 2.3 절을 인용하면 :
"URI에서 허용되지만 예약 된 용도가없는 문자는 예약되지 않은 문자라고합니다. 대문자 및 소문자, 십진수, 하이픈, 마침표, 밑줄 및 물결표를 포함합니다."
ALPHA DIGIT "-" / "." / "_" / "~"
RFC 3986은 이전 RFC 2396 보다 예약 된 구두점 수가 적습니다 .
주의해야 할 문자 세트는 reserved 및 unsafe 입니다.
예약 문자는 다음과 같습니다
- 앰퍼샌드 ( "&")
- 달러 ( "$")
- 더하기 부호 ( "+")
- 반점 (",")
- 슬래시 ( "/")
- 콜론 ( ":")
- 세미콜론 ( ";")
- 같음 ( "=")
- 물음표 ("?")
- 'At'기호 ( "@")
- 파운드 ( "#").
일반적으로 안전하지 않은 것으로 간주되는 문자 는 다음과 같습니다.
- 우주 (" ")
- 보다 작거나 큼 ( "<>")
- 열기 및 닫기 괄호 ( "[]")
- 열기 및 닫기 괄호 ( "{}")
- 파이프 ( "|")
- 백 슬래시 ( "\")
- 캐럿 ( "^")
- 퍼센트 ( "%")
나는 하나 이상을 잊어 버렸을 수 있으며, 이는 칼 V의 대답을 반향시킵니다. 장기적으로는 서버 및 시스템에서 허용되지 않는 문자를 유지하려고 시도하는 대신 허용되는 문자의 "화이트리스트"를 사용한 다음 문자열을 인코딩하는 것이 좋습니다.
특정 문자 (블랙리스트)를 제거하는 대신 일부 문자 (화이트리스트) 만 유지하는 것이 가장 좋습니다.
제대로 인코딩하는 한 기술적으로 모든 문자를 허용 할 수 있습니다. 그러나 질문의 정신으로 대답하려면 다음 문자 만 허용해야합니다.
- 소문자 (대문자를 소문자로 변환)
- 숫자, 0 ~ 9
- 대시 또는 밑줄 _
- 틸드 ~
다른 모든 것에는 잠재적으로 특별한 의미가 있습니다. 예를 들어 +를 사용할 수 있다고 생각할 수 있지만 공백으로 바꿀 수 있습니다. &는 특히 일부 다시 쓰기 규칙을 사용하는 경우에도 위험합니다.
다른 의견과 마찬가지로 자세한 내용은 표준 및 사양을 확인하십시오.
항상 안전
이것들은 기본적으로 도메인 이름을 제외한 모든 곳에서 안전합니다 (이론 / 사양).
목록에없는 것을 백분율로 인코딩하면 좋습니다.
A-Z a-z 0-9 - . _ ~ ( ) ' ! * : @ , ;
때로는 안전
특정 URL 구성 요소 내에서 사용될 때만 안전합니다. 주의해서 사용하십시오.
Paths: + & =
Queries: ? /
Fragments: ? / # + & =
절대 안전
URI 사양 (RFC 3986)에 따르면 다른 모든 문자는 백분율로 인코딩되어야합니다. 여기에는 다음이 포함됩니다.
<space> <control-characters> <extended-ascii> <unicode>
% < > [ ] { } | \ ^
최대 호환성이 문제가되는 경우 문자 세트를 AZ az 0-9-_로 제한하십시오.
(파일 이름 확장자에만 마침표 사용).
Looking at RFC3986 - Uniform Resource Identifier (URI): Generic Syntax, your question revolves around the path component of a URI.
foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment | _____________________|__ / \ / \ urn:example:animal:ferret:nose
Citing section 3.3, valid characters for a URI segment
are of type pchar
:
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
Which breaks down to:
ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded
"!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
":" / "@"
Or in other words: You may use any (non-control-) character from the ASCII table, except /
, ?
, #
, [
and ]
.
This understanding is backed by RFC1738 - Uniform Resource Locators (URL).
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
From the context you describe, I suspect that what you're actually trying to make is something called an 'SEO slug'. The best general known practice for those is:
- Convert to lower-case
- Convert entire sequences of characters other than a-z and 0-9 to one hyphen (-) (not underscores)
- Remove 'stop words' from the URL, i.e. not-meaningfully-indexable words like 'a', 'an', and 'the'; Google 'stop words' for extensive lists
So, as an example, an article titled "The Usage of !@%$* to Represent Swearing In Comics" would get a slug of "usage-represent-swearing-comics".
The format for an URI is defined in RFC 3986. See section 3.3 for details.
From an SEO perspective, hyphens are preferred over underscores. Convert to lowercase, remove all apostrophes, then replace all non-alphanumeric strings of characters with a single hyphen. Trim excess hyphens off the start and finish.
I had similar problem, I wanted to have pretty urls and reached to the conclusion that I have to allow only letters, digits, - and _ in urls. That is fine, then I wrote some nice regex and I realized that it recognizes all UTF8 chars are not letters in .NET and was screwed. This appears to be a know problem for .NET regex engine. SO I got to this solution:
private static string GetTitleForUrlDisplay(string title)
{
if (!string.IsNullOrEmpty(title))
{
return Regex.Replace(Regex.Replace(title, @"[^A-Za-z0-9_-]", new MatchEvaluator(CharacterTester)).Replace(' ', '-').TrimStart('-').TrimEnd('-'), "[-]+", "-").ToLower();
}
return string.Empty;
}
/// <summary>
/// All characters that do not match the patter, will get to this method, i.e. useful for unicode chars, because
/// .NET impl of regext do not handle unicode chars. So we use char.IsLetterOrDigit() which works nicely and we
/// return what we approve and return - for everything else.
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string CharacterTester(Match m)
{
string x = m.ToString();
if (x.Length > 0 && char.IsLetterOrDigit(x[0]))
{
return x.ToLower();
}
else
{
return "-";
}
}
I found it very useful to encode my url to a safe one when I was returning a value through ajax/php to a url which was then read by the page again.
PHP output with url encoder for the special character &
//PHP returning the sucess info of ajax request
echo "".str_replace('&','%26',$_POST['name'])." category was changed";
//javascript sending the value to url
window.location.href='time.php?return=updated&val='+msg;
//javascript/php executing the function printing the value of the url,
//now with the text normally lost in space because of the reserved & character.
setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');",360);
Hope anyone finds my little code extracts useful! :)
I think you're looking for something like "URL Encoding" - encoding a URL so that it's "safe" to use on the web:
Here's a reference for that. If you don't want any special characters, just remove any that require URL encoding:
http://www.w3schools.com/TAGS/ref_urlencode.asp
Between 3-50 characters. Can contain lowercase letters, numbers and special characters - dot(.), dash(-), underscore(_) and at the rate(@).
참고URL : https://stackoverflow.com/questions/695438/safe-characters-for-friendly-url
'Programing' 카테고리의 다른 글
호스트 요소에“클래스”를 추가하는 방법은 무엇입니까? (0) | 2020.06.07 |
---|---|
'--color'및 '--format specdoc'옵션을 유지하도록 RSpec을 전역 적으로 구성하는 방법 (0) | 2020.06.07 |
값이 홀수인지 또는 짝수인지 테스트 (0) | 2020.06.07 |
WebView에서 파일 업로드 (0) | 2020.06.07 |
Java : System.console ()에서 입력을 얻는 방법 (0) | 2020.06.07 |