Search code examples
.htaccesshttp-redirectmod-rewritehttp-status-code-301

Htaccess redirect with folders


I am trying to create a list with numerous redirects (301) and do not want to change the order manually. Unfortunately, certain 301 redirects don't really work:

RewriteEngine on

Redirect 301 "/en/kontakt/" https://www.example.com/kontakt/ 
Redirect 301 "/en/kontakt/132-start-page-en/gaesteinformation-en/" https://www.example.com/kontakt/'''

The first redirect works, the second one gives a 404.

200,https://,www.example.com/kontakt/
404,https://,www.example.com/kontakt/132-startseite-de/gaesteinformation-de/

If I swap the order, it works. What is the problem? Do you have any ideas?

Best regards Rudi


Solution

  • The mod_alias Redirect directive is prefix-matching and everything after the match is copied onto the end of the target URL. So, your first rule matches both requests (the second rule doesn't do anything) and in the case of the request for /en/kontakt/132-start-page-en/gaesteinformation-en/, everything after /en/kontakt/ is appended to the end of the target URL.

    You need to either:

    • Change the order of the directives (as you suggest) so the more specific directive is first.

    OR,

    • Change the directives to use RedirectMatch instead, which matches against a regex instead of simple prefix-matching.

    For example:

    RedirectMatch 301 ^/en/kontakt/$ https://www.example.com/kontakt/ 
    RedirectMatch 301 ^/en/kontakt/132-start-page-en/gaesteinformation-en/$ https://www.example.com/kontakt/
    

    Which can be combined into a single directive:

    RedirectMatch 301 ^/en/kontakt/(132-start-page-en/gaesteinformation-en/)?$ https://www.example.com/kontakt/