如何使URL mod重定向(.htaccess)更愚蠢


How to make a URL mod redirect (.htaccess) more fool proof?

我有以下重定向,它们部分工作正常,但不是很愚蠢。

URL(有效):

example.com/test123
example.com/test123/hello

.htaccess我有:

RewriteRule ^('w+)/?$ /index.php?id=$1 [L,QSA]
RewriteRule ^('w+)/('w+)/?$ /index.php?id=$1&mode=$2 [L,QSA]

虽然它工作得很好,但当用户输入"example.com/test123",而不是"example.com/stest123/"时。出于某种原因,在URL末尾加上"/"会将页面带到404。

上述(.htaccess)重定向条目的以下URL(不起作用)(因为末尾有"/"的原因):

example.com/test123/
example.com/test123/hello/

我该怎么解决这个问题?

正如@anubhava所观察到的

你的规则对我有效,即使你有URL404错误。所以请测试,通过添加一行,通过取消激活多视图:

Options -MultiViews
RewriteEngine On
RewriteRule ^('w+)/?$ /index.php?id=$1 [L,QSA]
RewriteRule ^('w+)/('w+)/?$ /index.php?id=$1&mode=$2 [L,QSA]

同时,重写http://www.example.com/test123/hello/

你应该重新编程你的HTML文档,这是一个痛苦的改变:所有的资源文件都必须以绝对路径使用,比如*.css、*.js、*.png……而且它们不能被重写。在这种情况下,style.css将与RewriteRules不匹配,因此保持不变-我们很幸运!

<link rel="stylesheet" type="text/css" href="/mystyles/style.css" />

代替相对路径:

<link rel="stylesheet" type="text/css" href="mystyles/style.css" />

*.js、*.png、…也需要同样的更改

可以假设从不需要尾部斜杠。如果是这种情况,您可以添加一个重写规则来删除尾部斜杠,从而使重定向始终有效。

RewriteRule ^(.*)/$ $1 [R=301,L]

确保重写发生在重定向之前!