So I’m trying to get mod_rewrite to do a few different things, and I’m not quite there with it. I’d like to:
- Remove file extensions from the URLs (in this case, .shtml)
-
Rewrite certain URLs like so:
/dashboard -> /ui/dashboard/index.shtml /dashboard/ -> /ui/dashboard/index.shtml /dashboard/list -> /ui/dashboard/list.shtml /dashboard/list/ -> /ui/dashboard/list.shtml /workspace -> /ui/workspace/index.shtml /workspace/ -> /ui/workspace/index.shtml /account/manage -> /ui/account/manage.shtml /account/manage/ -> /ui/account/manage.shtml -
Either add or remove a trailing slash ( I don’t care which, as long as it’s consistent)
What I currently have gets me about 90% of the way there. In my .htaccess file, I’ve got the following:
DirectoryIndex index.shtml index.html index.htm
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
# Get rid of the /ui/ in the URLs
RewriteRule ^(account|workspace|dashboard)([a-zA-Z0-9\-_\.\/]+)?$ /ui/$1$2 [NC,L]
# Add the trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]
# Remove the shtml extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.shtml -f
RewriteRule ^([^\.]+)/$ $1\.shtml
</IfModule>
Now the issues I’m running into are twofold:
First, if I try to access one of the index pages outlined in the directories listed in step 2 above, as long as I do it with a trailing slash, it’s fine, but if I omit the trailing slash, the URL rewrites incorrectly (the page still loads, however). For example
/dashboard/ remains /dashboard/ in the address bar.
/dashboard rewrites to /ui/dashboard/ in the address bar.
How can I get these index.shtml pages to keep the address bar consistent?
Second, when I try to access a page other than the directory index in one of the rewritten directories, and I include a trailing slash, it gives me a 404 error. For instance:
/dashboard/list/
throws the 404 error:
The requested URL /ui/dashboard/list.shtml/ was not found on this server.
Any help to get this working properly that you can offer is much appreciated.
So I’ve figured out an approach that works for what I need. Here’s the .htaccess I came up with, commented inline:
Not sure if this is the most efficient way to do this, but it’s working for my needs. Thought I’d share it here in case it helps anyone else.