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

问题描述:

So I have managed to rewrite urls using the .htaccess file but the redirection messes up the url. For example I try to rewrite this:

localhost/mysite/public_html/class/5/

into this:

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

and I use the following lines in the .htaccess file:

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

but the browser redirects me here (I am using wamp on Windows 7):

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

Which is wrong and gets me a 403 error. What should I do?

It's unbelievable. The error was a result of Firefox's caching. I used Chrome and it was ok. So I cleared Firefox's cache and everything worked fine.

The problem must come from the ./ in your replacement function (./public_html/index.php). A rewrite rule matches the regex you place between ^ and $ and then replaces ONLY that with your second part. I'm assuming you already have some sort of rewritecond before the rule, so try removing the "./"

Try changing your rewritecond to:

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

Which means that if the requested URL is not a file or directory, then it will follow through and try your rewriterule

Your rule needs to look like this:

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

I don't know which rules you've got before, but your minimal htaccess should be this one :

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]

Avoid using ./ in your rules, and don't forget the location path must include your mysite folder