user3769800
user3769800

Reputation: 25

.htaccess rule skipping a subfolder in the redirect

Here’s my rewrite rule:

RewriteEngine on
RewriteRule ^dev/([^/]+)/ dev/index.php?test=$1 [NC]

However, instead of changing the url from www.test.com/dev/asdf to www.test.com/dev/index.php?test=asdf, what happens instead is that we get www.test.com/index.php?test=asdf. So basically the dev/ part in the rewrite rule is just skipped.

The intended effect is to have dev/variable/ be parsed as a get variable, so it gets changed to dev/index.php?test=variable.

Upvotes: 2

Views: 31

Answers (2)

Giacomo1968
Giacomo1968

Reputation: 26066

Try this mod_rewrite ruleset instead:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(dev/index.php)$ [NC]
RewriteRule ^dev/?([^/]*)$ /dev/index.php?test=$1 [R,L,NC]

The second line which has the RewriteCond is to ensure that you don’t have an endless loop of dev/[something] going to dev/index.php which will result in an internal server error. The R flag sets a real redirect to /dev/index.php?test= rather than just passing parameters behind the scenes.

And one benefit of the R flag is you debug this stuff using curl -I from the command line like this to show you the actual headers being returned. I’m using localhost:8888 on my local MAMP, FWIW:

curl -I localhost:8888/dev/asdf

Now the resulting headers are as follows:

HTTP/1.1 302 Found
Date: Sun, 29 Jun 2014 04:15:31 GMT
Server: Apache/2.2.23 (Unix) mod_ssl/2.2.23 OpenSSL/0.9.8y DAV/2 PHP/5.4.10
Location: http://localhost:8888/dev/index.php?test=asdf
Content-Type: text/html; charset=iso-8859-1

The HTTP/1.1 302 Found means that a 302 temporary redirect will be happening. And the Location header shows the proper final destination of http://localhost:8888/dev/index.php?test=asdf.

Then in my test setup, I placed a dev/index.php file that contains this simple PHP code:

<?php

echo '<pre>';
print_r($_GET);
echo '</pre>';

?>

So a call to localhost:8888/dev/asdf creates the final URL of http://localhost:8888/dev/index.php?test=asdf and the output of that PHP script shows that the asdf is properly being passed as desired:

Array
(
    [test] => asdf
)

Upvotes: 0

zx81
zx81

Reputation: 41838

It could be several things: .htaccess is in the wrong folder, incorrect RewriteBase set up elsewhere, or the url is getting rewritten by another rule.

Make sure to place the .htaccess in your DOCUMENT_ROOT folder (the one above dev).

Then try this:

RewriteEngine on
RewriteBase /
RewriteRule ^dev/([^/]+)/ dev/index.php?test=$1 [NC,L]

Upvotes: 2

Related Questions