I had already written most of this before you posted your solution. Posting anyway as a more general solution that readers may find useful.
How can I make the request for page1.php
to show www.example.com/page1
instead of www.example.com/subdir1/subdir2/page1.php
?
You do this by physically changing the URLs in your application, not in .htaccess
. Once the URLs have been changed in your application, the request is then for www.example.com/page1
, the visible URL that is shown to your users (not page.php
). You then use mod_rewrite in .htaccess
to internally rewrite the visible URL back to the real/hidden filesystem path: /subdir1/subdir2/page1.php
. (But I suspect you already know this, since your code is doing the right kind of thing.)
In your file hierarchy diagram, you appear to show subdir2
at the same level as subdir1
? However, your code and URL structure suggests subdir2
is a subdirectory of subdir1
. I'll assume the later.
You basically need to do two things:
Rewrite all requests to /subdir1/subdir2/
(except for requests that map directly to files or directories).
Append the .php
file extension to requests that don't already have a file extension.
Try something like the following in the .htaccess
file in the document root, ie. mysiteroot/.htaccess
.
RewriteEngine On
# If the request has already been rewritten
# Or maps to an existing file then stop here.
# (Can't test for dir here since would not rewrite the doc root)
RewriteCond %{ENV:REDIRECT_STATUS} . [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# No file extension on request then append .php and rewrite to subdir
RewriteCond %{REQUEST_URI} /(.+)
RewriteRule !\.[a-z0-4]{2,4}$ /subdir1/subdir2/%1.php [NC,L]
# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /subdir1/subdir2/$1 [L]
Any request for /path/to/file
(that does not directly map to a file) gets internally rewritten to /subdir1/subdir2/path/to/file.php
.
The first RewriteCond
directive ensures we don't rewrite requests that have already been rewritten to the subdirectory, thus preventing a rewrite loop.