我正在做一个有文章的网站,我需要文章有“友好”的url,基于标题。

例如,如果我的文章标题是“文章测试”,我希望URL是http://www.example.com/articles/article_test。

但是,文章标题(与任何字符串一样)可以包含多个特殊字符,这些字符不可能直接放在我的URL中。比如说,我知道?或#需要被替换,但我不知道所有其他。

url中允许使用哪些字符?什么东西是安全的?


当前回答

看看RFC3986 -统一资源标识符(URI):通用语法,你的问题围绕着URI的路径组件。

foo: / / example.com: 8042 / / / ? name =雪貂#鼻子

     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

引用3.3节,URI段的有效字符类型为pchar:

Pchar = unreserved / pct-encoded / sub-delims / ":" / "@"

具体分为:

Alpha / digit / "-" / "."/ "_" / "~" pct-encoded “啊!”/ "$" / "&" / "'" / "(" / ")"/ "*" / "+" / " " / ";"/“=” ":" / "@"

或者换句话说:您可以使用ASCII表中的任何(非控制-)字符,除了/,?,#,[和]。

这一理解得到了RFC1738 -统一资源定位符(URL)的支持。

其他回答

您需要注意两组字符:保留字符和不安全字符。

保留字符为:

&(“&”) 美元(美元) 加号(“+”) 逗号(,) 正斜杠("/") 冒号(“:”) 分号(“;”) = (" = ") 问号(“?”) “At”符号(“@”) 英镑(“#”)。

一般认为不安全的字符有:

空格(" ") 小于大于("<>") 左右括号("[]") 前后大括号("{}") 管(“|”) 反斜杠(\) 插入符号(“^”) 百分比(%)

我可能忘记了一个或多个,这导致我重复卡尔V的答案。从长远来看,您最好使用允许字符的“白名单”,然后对字符串进行编码,而不是试图与服务器和系统不允许的字符保持一致。

我发现当我通过Ajax/PHP返回一个值到一个URL,然后由页面再次读取时,将我的URL编码为一个安全的URL非常有用。

PHP输出与URL编码器的特殊字符&:

// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";

// JavaScript sending the value to the 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);

unreserved = ALPHA / DIGIT / "-" / "."/ "_" / "~"

3-50个字符之间。可以包含小写字母、数字和特殊字符——点(.)、破折号(-)、下划线(_)和@。

URI的格式在RFC 3986中定义。详见3.3节。