Mod_Rewrite with Relative Path Redirects

2020-03-23 18:32发布

问题:

I have this rule in an .htaccess file located in a directory named clips/:

RewriteRule ^mlk/?$ segment/index.php?clip=1 [R=301,QSA,L]

What I am intending is that when someone visits http://example.local/clips/mlk they are redirected to http://example.local/clips/segment/index.php?clip=1

What actually happens is that when someone visits example.local/clips/mlk they are redirected to example.local/var/www/example/clips/segment/index.php?clip=1

I'm not sure why it's doing this. If I change the rewrite rule to this:

RewriteRule ^mlk/?$ /segment/index.php?clip=1 [R=301,QSA,L]

The user is redirected to example.local/segment/index.php?clip=1, which is still incorrect. I don't want to have to specify an absolute path in the case of these files being moved around the website's directory tree. How can I get this to work relatively instead of absolutely?

回答1:

Try adding a RewriteBase directive as below

RewriteEngine On
RewriteBase /clips/

RewriteRule ^mlk/?$ segment/index.php?clip=1 [R=301,QSA,L]

EDIT

but is there any way to get this to work without using a RewriteBase directive

You could also try

RewriteEngine On


RewriteCond %{REQUEST_URI} ^(/[^/]+/) [NC] 
RewriteRule ^mlk/?$ http://%{HTTP_HOST}%1segment/index.php?clip=1 [R=301,QSA,L]