Search code examples
.htaccess

getting a internal server error on redirect 301


My old page url looks like this

https://blabla.com/us/sample-data/us/

my new url looks like this

https://blabla.com/us/data/sample/us/

I added this into my htaccess

<IfModule mod_rewrite.c>
Redirect 301 ^sample-data/us/ /data/sample/us/ [NC,L]
</IfModule>

but i'm getting a internal server error

the 1st us in the url is dynamic depending on country user is from. and the 2nd us is the countries sample data. which is a list of 10 countries at the moment. could be more.

i tried

RewriteRule ^sample-data/us/ /data/sample/us/ [L,R=301,NC]

but no luck either. it redirects too

https://blabla.com/data/sample/us/ missing the 1st /us/

how do get this redirect working? Thanks


Solution

  • <IfModule mod_rewrite.c>
    Redirect 301 ^sample-data/us/ /data/sample/us/ [NC,L]
    </IfModule>
    

    but i'm getting a internal server error

    Because that directive is syntactically invalid. The [NC,L] argument is a parameter belonging to the mod_rewrite RewriteRule directive. Redirect is a mod_alias directive - there is no such "flags" parameter with the Redirect directive.

    RewriteRule ^sample-data/us/ /data/sample/us/ [L,R=301,NC]
    

    but no luck either. it redirects too

    https://blabla.com/data/sample/us/ missing the 1st /us/

    You appear to be missing the 1st /us/ (virtual path segment) from your directives, so I don't see how this is redirecting at all (unless you are seeing a cached response, or something else is performing the redirect)? This .htaccess file is presumably in the document root and you are presumably requesting the URL /us/sample-data/us/ and the first /us/ is virtual - so the directive above cannot possibly do anything?

    If the first path segment is variable and you need to redirect to the same path segment and assuming this consists of two lowercase a-z letters then try the following instead:

    RewriteRule ^([a-z]{2})/sample-data/us/ /$1/data/sample/us/ [R=302,L]
    

    But what about the 2nd /us/ - is that not also variable? Should the 1st and 2nd instance of /XX/ (two letters) be the same?

    Test first with 302 (temporary) redirect to avoid potential caching issues. You will need to clear your browser cache before testing.

    I've removed the NC flag - should this really be a case-insensitive match?

    Note that if you have existing directives in your .htaccess file then the order is important. Generally, external redirects need to go near the top, certainly before your front-controller.