Home > OS >  Redirect all subpages to main page using htaccess
Redirect all subpages to main page using htaccess

Time:05-22

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?

CodePudding user response:

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:

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.

CodePudding user response:

Try this, it works in my ERP system.

RewriteRule ^(.*)$ http://www.example.com/ [L,R=301]
  • Related