My htaccess redirects with regex aren't working

24 Views Asked by At

I have the following redirect in my htaccess:

Redirect 301 "^/city/(.*)-north-carolina$" "https://example.com/US/NC/$1-north-carolina-hotels.php"

When I enter example.com/city/asheville-north-carolina I don't get the redirect like I should. Something wrong with my syntax or does something need to happen with RewriteCond?

I've tried various version of the syntax, nothing

1

There are 1 best solutions below

0
Patrick Janser On

The Redirect directive only takes a static URL as input.

To solve it, either :

  • Replace Redirect by RedirectMatch :

    RedirectMatch 301 ^/city/(.*)-north-carolina$ https://example.com/US/NC/$1-north-carolina-hotels.php
    

    Here, RedirectMatch will receive the leading slash of the URL.

Or

  • Use a RewriteRule :

    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^city/(.*)-north-carolina$ https://example.com/US/NC/$1-north-carolina-hotels.php [R=301,L]
    

    In this case, RewriteRule receives the path without the leading slash.