使用localhost中的.htaccess文件重写url


Rewrite urls with .htaccess file in localhost

所以我已经设法使用.htaccess文件重写了url,但重定向会弄乱url。例如,我试图重写这个:

localhost/mysite/public_html/class/5/

进入这个:

localhost/mysite/public_html/index.php?v=class&id=5

我在.htaccess文件中使用了以下行:

RewriteRule ^public_html/([A-Za-z]+)/([0-9]+)/?$ ./public_html/index.php?v=$1&id=$2 [L,R]

但浏览器将我重定向到这里(我在Windows 7上使用wamp):

localhost/C:/wamp/www/mysite/public_html/index.php?v=class&id=5

这是错误的,给了我403的错误。我该怎么办?

您的规则需要如下所示:

RewriteRule ^public_html/([A-Za-z]+)/([0-9]+)/?$ /public_html/index.php?v=$1&id=$2 [L,R]

问题一定来自。/在替换函数(./public_html/index.php)中。重写规则匹配您放置在^和$之间的正则表达式,然后用第二部分只替换它。我假设你在规则之前已经有了某种重写条件,所以试着删除"./"

尝试将您的重写条件更改为:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

这意味着,如果请求的URL不是文件或目录,那么它将执行并尝试您的重写

我不知道你以前有哪些规则,但你的最小htaccess应该是这个:

RewriteEngine On
RewriteBase /mysite/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^public_html/([A-Za-z]+)/([0-9]+)/?$ /mysite/public_html/index.php?v=$1&id=$2 [L,R]

避免在规则中使用./,并且不要忘记位置路径必须包括您的mysite文件夹

真是难以置信。该错误是Firefox缓存的结果。我用的是Chrome浏览器,它还可以。所以我清除了Firefox的缓存,一切都很好。