You will need to ensure that MultiViews
is disabled before this will work correctly, as this will tend to conflict with your mod_rewrite directives. Add this in your .htaccess file:
Options +FollowSymLinks -MultiViews
(FollowSymLinks
needs to be enabled for mod_rewrite to work, so just to be sure.)
Then, something like what you already have looks reasonable:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.jsp -f
RewriteRule (.+)/$ $1.jsp [L]
I've made the trailing slash mandatory on the URL (otherwise you potentially have two URLs accessing the same content - duplicate content).
UPDATE: To redirect any requests to the .jsp
URL to the canonical URL (ie. without the extension and with a trailing slash) then something like the following (similar to what you had in your question) would need to go before the directives above:
RewriteCond %{THE_REQUEST} \.jsp\s
RewriteRule (.+)\.jsp$ /$1/ [R=301,L]
This is only strictly necessary if the .jsp
URLs had been indexed or externally linked to. If this is a new site then this step is optional.
It is more efficient to match what you can with the RewriteRule
pattern (ie. (.+)\.jsp$
), rather than have a catch-all regex here. The THE_REQUEST
condition ensures that this only applies to initial requests and not rewritten requests - thus preventing a redirect loop.
So, in summary:
# Disable MultiViews
Options +FollowSymLinks -MultiViews
RewriteEngine On
# Remove file extension from URLs (external redirect)
RewriteCond %{THE_REQUEST} \.jsp\s
RewriteRule (.+)\.jsp$ /$1/ [R=301,L]
# Internally rewrite extensionless URLs back to ".jsp"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.jsp -f
RewriteRule (.+)/$ $1.jsp [L]
DEBUGGING: To help with debugging the above, add the following directive below the RewriteEngine On
directive and check the environment variables (MOD_REWRITE_THE_REQUEST
and MOD_REWRITE_URL_PATH
) in your server-side code:
RewriteCond %{THE_REQUEST} (.*)
RewriteRule (.*) - [E=MOD_REWRITE_THE_REQUEST:%1,E=MOD_REWRITE_URL_PATH:$1]
What do these environment variables contain when you access a .jsp
URL?
example.com/xyz/
? The first code block references.php
extensions and the second.html
, whereas you are using.jsp
- so even without looking at the code it's clear they are not going to work? But anyway, when you say "not working correctly", please be specific... what happens exactly, an errors? – MrWhite Sep 7 '16 at 7:59