Reputation: 1637
I need to redirect multiple URLs with hyphens in them, through .htaccess
.
Here is the current .htaccess
file:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ -
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php
RewriteRule ^/([0-9]+).*$ /$1/ [R,L]
Here is an example of the URL format I am trying to redirect:
http://www.example.com/52346-3/
Should redirect to
http://www.example.com/52346/
I am new to .htaccess
and just can't seem to get that last line quite right.
Upvotes: 1
Views: 84
Reputation: 45829
RewriteRule ^/([0-9]+).*$ /$1/ [R,L]
This redirect will need to go near the start of the .htaccess
file, before the existing rewrites. You also need to remove the slash prefix from the RewriteRule
pattern, otherwise it will never match in a directory (.htaccess
) context.
So, assuming you simply want to strip everything after the first group of digits (including the hyphen), then try something like the following:
RewriteRule ^(\d+)- /$1/ [R,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
\d
is a shorthand character class for [0-9]
. .*$
is the same as not including a trailing pattern at all.
I've also added the L
flags - important for the second RewriteRule
.
UPDATE: Added hyphen to the end of the RewriteRule
pattern to explicitly match a hyphen (and to avoid a redirect loop).
Upvotes: 2