apache.htaccesshttp-redirecthttp-status-code-301

301 Redirect a URL to the home page using htaccess not working


I am trying to 301 redirect from:https://www.domain.co.uk/?404;http://www.domain.co.uk:80/sn-down-to-earth.html to https://www.domain.co.uk/

In my .htaccess file I have the following:

Redirect 301 "/?404;http://www.domain.co.uk:80/sn-down-to-earth.html" https://www.domain.co.uk/

I have a few hundred redirects in the .htaccess file already which all work fine. I think its to do with the ? or ; in the URL?


Solution

  • I think its to do with the ? or ; in the URL?

    Yes, it is to do with the ?, which delimits the query string in the URL.

    The mod_alias Redirect directive matches against the URL-path only, not the query string (everything after the first ?). To match the query string you need to use mod_rewrite with a condition that checks against the QUERY_STRING server variable. In your example, the URL-path is empty.

    Try the following instead:

    RewriteEngine on
    
    RewriteCond %{QUERY_STRING} =404;http://www.domain.co.uk:80/sn-down-to-earth.html
    RewriteRule ^$ / [QSD,R=301,L]
    

    The = prefix on the CondPattern (2nd argument to the RewriteCond directive) makes this a lexicographical (exact match) string comparison (as opposed to a regex).

    The QSD (Query String Discard) flag removes the query string from the redirect response. This requires Apache 2.4. The query string is otherwise passed through by default.