Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod_Rewrite with Relative Path Redirects

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?

like image 655
Ian Hunter Avatar asked Feb 01 '12 19:02

Ian Hunter


People also ask

What is RewriteCond and RewriteRule?

There are two main directive of this module: RewriteCond & RewriteRule . RewriteRule is used to rewrite the url as the name signifies if all the conditions defined in RewriteCond are matching. One or more RewriteCond can precede a RewriteRule directive.

What is NC in RewriteCond?

NC|nocase. Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI. In the example below, any request for an image file will be proxied to your dedicated image server.

What is Rewriteengine on Apache?

A rewrite engine is a component of web server software that allows you to rewrite or redirect uniform resource locators (URLs). The most popular rewrite engine is the Apache HTTP server's mod_rewrite. There are other web servers, such as nginx or lighttpd, that provide similar functions.


1 Answers

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]
like image 121
Ulrich Palha Avatar answered Sep 24 '22 12:09

Ulrich Palha