使用 RewriteRules 重写编码的 URL

Rewrite encoded URLs with RewriteRules

我正在使用以下重写规则重写“domain.com/lolmeter/platformValue/usernameValue”(platformValue 和 usernameValue 是用户通过文本输入请求的值):

RewriteRule ^lolmeter/([a-zA-Z0-9]*)/([a-zA-Z0-9]*)$ /lolmeter.html?platform=&username= [L]
    
button.href = lolmeter/platformValue/usernameValue

我注意到当用户输入空格或其他非字母数字值时,它会自动使用“%”符号进行编码,因此我尝试重写规则以接受它们,例如:

RewriteRule ^lolmeter/(([a-zA-Z0-9]|%)*)/(([a-zA-Z0-9]|%)*)$ /lolmeter.html?platform=&username= [L]

但它不起作用,我认为是因为括号。那么我应该使用哪个符号作为内部“|” ?

P.S:是否有更流行或更现代的更改 URL 的方法?

RewriteRule ^lolmeter/(([a-zA-Z0-9]|%)*)/(([a-zA-Z0-9]|%)*)$ /lolmeter.html?platform=&username= [L]

RewriteRule 模式 匹配 %-解码的 URL-path。因此,如果请求的 URL-path 中存在编码 space(即 %20),则规则与文字 space,不是%20.

您可以在正则表达式中的字符 class 中使用 \s shorthand 字符 class 来匹配任何白色 space 字符。

例如:

RewriteRule ^lolmeter/([a-zA-Z0-9\s]+)/([a-zA-Z0-9\s]*)$ /lolmeter.html?platform=&username= [L]

请注意,我在 second/middle 路径段上使用量词 + 而不是 *,因为我假设中间路径段不是可选的。请注意,URL-path 中的多个连续斜杠在匹配正则表达式之前也会减少,因此如果省略中间路径段,则传递的 username 将被视为 平台,我确定这不是本意。

另请注意,在上面的 space 不是 re-encoded 在结果重写中。使用 B 标志将 re-encode space 作为查询字符串中的 +。 (如果您特别需要 space 为 re-encoded 作为 %20 然后使用 BNP 标志 - 需要 Apache 2.4。 26)

P.S: Is there a more popular or modern way for changing URLs?

不确定您的意思,但 Apache 上的 mod_rewrite 是 URL 重写模块。一直都是,可能永远都是。

但是,您不一定需要按照您已经完成的方式重写请求,尽管您可能仍然希望以类似的方式匹配 URL(取决于您正在做的其他事情)。您也许可以将请求重写为 lolmeter.html 并让您的脚本直接解析 URL-path,而不是查询字符串。

或者,我认为“现代方式”是将 所有内容 重写为“front-controller” - 一个解析 URL 的入口脚本并适当地“路由”请求。这避免了必须在 .htaccess 中进行大量重写。虽然这不是什么“新事物”,但它可能变得更加普遍。许多 CMS/frameworks 使用此模式。