Search code examples
apache.htaccess

htaccess file format gives internal server error on some redirects


I have a .htaccess file with the following content;

My .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^/?$ https://meervoormamas.nl [R=301,L]
RewriteRule ^/dossiers/autisme/?$ https://meervoormamas.nl/kind/ontwikkeling/ R=301,L]
RewriteRule ^/schoolkind/opvoeding/7\-tips\-om\-uw\-kinderen\-te\-begeleiden\-op\-sociale\-netwerken/?$ https://meervoormamas.nl/kind/opvoeding/7-tips-om-uw-kinderen-te-begeleiden-op-sociale-netwerken/ R=301,L]
</IfModule>

Where the first RewriteRule does work, if I type in https://mamalove.nl it redirects to https://meervoormamas.nl But with the second RewriteRule(a category in WP) gives an Internal server error, and also with the third RewriteRule (a post).

What am I doing wrong?


Solution

  • As well as the missing opening [ that delimits the flags (3rd) argument on the RewriteRule directive, as mentioned in comments, in a directory (.htaccess) context the URL-path matched by the RewriteRule pattern does not start with a slash, so these rules will never match.

    Other minor issues:

    • You are missing the trailing slash after the domain in the first rule's substitution string.
    • No need to backslash-escape literal hyphens when used outside of a regex character class (3rd rule).
    • The RewriteBase directive is not being used here.
    • The <IfModule> wrapper is not required.

    Try the following instead:

    RewriteEngine On
    
    RewriteRule ^$ https://meervoormamas.nl/ [R=301,L]
    RewriteRule ^dossiers/autisme/?$ https://meervoormamas.nl/kind/ontwikkeling/ [R=301,L]
    RewriteRule ^schoolkind/opvoeding/7-tips-om-uw-kinderen-te-begeleiden-op-sociale-netwerken/?$ https://meervoormamas.nl/kind/opvoeding/7-tips-om-uw-kinderen-te-begeleiden-op-sociale-netwerken/ [R=301,L]
    

    Since you appear to be redirecting to a similar URL-path in the 3rd rule, this can be "simplified" by avoiding repetition. For example:

    RewriteRule ^school(kind/opvoeding/7-tips-om-uw-kinderen-te-begeleiden-op-sociale-netwerken)/?$ https://meervoormamas.nl/$1/ [R=301,L]
    

    $1 is a backreference that contains everything in the captured group in the preceding pattern. It basically just removes the "school" prefix and ensures the redirected URL ends in a trailing slash.

    If these rules are being used on an existing WordPress site then these directives must go at the top of the .htaccess file, before the # BEGIN WordPress section.