Richelliot Richelliot - 11 months ago 63
Apache Configuration Question

.htaccess redirect for specific URL structures

I have the following URL:

I need it to redirect to the following URL

Essentially If there is a trailing number element to the URL (in this case
) I need the
part of the URL to be removed.

Note: ONLY if there is a trailing number

Answer Source

Try the following (using mod_rewrite) near the top of your .htaccess file at

RewriteEngine On
RewriteRule ^tutorials/([^/]+/\d+)$$1 [R=302,L]

In this case, the trailing "number" can be 1 or more digits. If it is only a single digit (as in your example) then this should be simplified (change \d+ to \d). The $1 is a backreference to the captured group in the RewriteRule pattern.

Note that this is a 302 (temporary) redirect, if this is intended to be permanent then change to 301 when you are sure it's working OK. 301s are cached by the browser so can make testing problematic.

UPDATE: To allow for an optional trailing slash on the source URL then add /? near the end of the RewriteRule pattern, like so:

RewriteRule ^tutorials/([^/]+/\d+)/?$$1 [R=302,L]

This notatably strips that optional trailing slash from the redirect target. (Thus avoiding any duplicate content issues.)