Search code examples
.htaccessmod-rewritehttp-redirectredirectmode

.htaccess/mod_rewrite 301 problem


I have a website with the following mod_rewrite rules in the .htaccess file:

RewriteRule ^web-design/case-studies/(.+)/$  work.php?slug=$1  [L,NC]
RewriteRule ^web-design/case-studies/        work.php          [L,NC]

What I'm wanting to do is set up a 301 redirect for any requests such as domain.com/web-design (with or without trailing slash) and redirect to example.com/web-design/case-studies/ (with trailing slash).

Unfortunately, the combination of Redirect and RedirectMatch rules I've tried seem to conflict with RewriteRules I have and end up with a redirect loop.

Regular expressions really isn't my thing, but I'm guessing I'll need a RewriteMatch rule to match requests that start with /web-design but don't also contain /case-studies? How would this be accomplished in .htaccess?


Solution

  • Please try these rules in your .htaccess rules:

    RewriteEngine on
    Options +FollowSymlinks -MultiViews
    
    RewriteRule ^web-design/?$ /web-design/case-studies/          [L,NC]
    
    RewriteRule ^web-design/case-studies/?$ /work.php             [L,NC]
    
    RewriteRule ^web-design/case-studies/(.*)$ /work.php?slug=$1  [L,NC,QSA]
    

    It is important to use QSA in last rule to not to loose existing QUERY parameters. I have tested these rules and they seem to be working fine. Trailing slash is optional in first 2 rules as per your requirements.