重写基础:从特定的 url 到另一个特定的 url

Rewriting basic: from specific url to another specific url

我问的是非常基本的问题,我认为应该可以,但我不知道为什么不行。

基本上,我需要这些 urls(1) 到 301 重定向到这些 others(2)

这是我的方法:

RewriteRule ^/es/madrid/ https://example.com/es/madrid-es/ [R=301,L]
RewriteRule ^/es/ibiza/ https://example.com/es/ibiza-es/ [R=301,L]
RewriteRule ^/es/madrid/ https://example.com/es/madrid-es/ [R=301,L]
RewriteRule ^/es/ibiza/ https://example.com/es/ibiza-es/ [R=301,L]

.htaccess 文件中,RewriteRule 模式 匹配的 URL-path 不以斜杠开头。所以上面的指令永远不会匹配请求的 URL,所以不会做任何事情。

换句话说,改为这样做:

RewriteRule ^es/madrid/ https://example.com/es/madrid-es/ [R=301,L]
RewriteRule ^es/ibiza/ https://example.com/es/ibiza-es/ [R=301,L]

请注意这些规则重定向 /es/madrid/<anything> - 这是故意的吗?否则,要完全匹配 URL-path 只有包含 end-of-string 锚点。例如。 ^es/madrid/$.


但是,您可以将这两个规则结合起来。例如:

RewriteRule ^(es)/(madrid|ibiza)/ https://example.com//-/ [R=301,L]

其中 </code> 和 <code> 反向引用对应于前面 RewriteRule pattern.[= 中捕获的组(带括号的子模式) 25=]


旁白: 对于任何双字符语言代码和 place 更进一步,您可以这样做:

RewriteRule ^([a-z]{2})/(\w+)/ https://example.com//-/ [R=301,L]

这会将 /<lang>/<place>/<anything> 重定向到 /<lang>/<place>-<lang>/,其中 <lang> 是任意两个字符的语言代码。