Htaccess RewriteRule + 301

TomDowning asked
.htaccess mod-rewrite

We have a rewrite rule setup to map /spaces/test.php to /areas/spaces/test/ as follows:

    RewriteRule ^areas/spaces/?$ spaces/$1.php

This is so the URL is mapped differently, but the underlying logic / code is still spaces/test.php .

So if we now access areas/spaces/test/ or spaces/test.php they both work. But.. I want a 301 to redirect spaces/test.php > areas/spaces/test/ .

Is this possible?


You can use the following rewrite rules to accomplish both things you desire.

RewriteRule ^spaces/([^/.]+).php$ /areas/spaces/$1/ [QSA,R=301,L]
RewriteRule ^areas/spaces/?$ spaces/$1.php [L]

I’ll walk you through the first line that I added:

  • A request for ^spaces/([^/.]+).php$
  • Is rewritten to /areas/spaces/$1/
  • But instead of an internal rewrite, use a redirect R=301
  • QSA tells Apache to append any query string that was passed onto the new location as well.
  • And L tells Apache to stop rewriting on that line when it matches, this way a redirect occurs and rewriting stops. On the next request for the proper location, the second line will match as you desire, so that internally it’s the .php file handling the request.

See also: official mod_rewrite docs

Share This
Posted in: