skip to Main Content

I want to redirect all subpages to main page. I tried with code:

RewriteEngine On
RewriteRule .+ http://www.example.com [r=301,nc,l]

All subpages are redirected except these that include question mark, for example, http://www.example.com/?123 is not redirected. How to modify my code to redirect also those URLs?

2

Answers


  1. You need to redirect any non-empty URL-path OR the homepage (empty URL-path) with a query string. You should also remove the query string as part of the redirect (your rule currently preserves the query string from the initial request).

    For example, try the following instead:

    # Redirect everything to the homepage (same domain)
    RewriteCond %{REQUEST_URI} ^/. [OR]
    RewriteCond %{QUERY_STRING} .
    RewriteRule ^ http://www.example.com/ [QSD,R=301,L]
    

    The above states… for all URL-paths where the URL-path consists of at least one character (after the initial slash) OR contains a query string then redirect to the root.

    The QSD flag discards the original query string from the request.

    The NC flag on the rule is superfluous, since you aren’t matching specific letters anyway.

    Aside: However, I would question the motives for doing something like this. Search engines (Google) will see mass redirects to the homepage as soft-404s, so there is no SEO benefit in doing this and it can often be confusing for users if they are following a link that previously existed. A meaningful 404 response is usually the preferred option in this scenario.


    UPDATE:

    If i would like to use this code also to redirect to other domain what should i change or add to redirect also main page?

    Assuming the other domain also points to a different server then you just need to remove the two conditions on the above rule to redirect everything and remove the query string.

    For example:

    # Redirect everything to the homepage on an external domain
    RewriteRule ^ http://www.example.com/ [QSD,R=301,L]
    
    Login or Signup to reply.
  2. Try this, it works in my system.

    RewriteRule ^(.*)$ http://www.example.com/ [L,R=301]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search