简体   繁体   中英

apache redirect to naked (non-www) domain messes up pages handler

all the urls in my website actually go through a PHP page that handles them by the page GET parameter (ie domain.com/sub/test is actually domain.com/page_handler.php?page=sub/test ). files or directories that exist don't go through the handler.

I've been trying to 301 redirect all www.domain.com requests to domain.com for improving SEO etc.

the problem is that this doesn't seem to work, no matter what rule I use and where I put it. this is the .htacess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#THIS IS THE DISCUSSED RULE:
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]


RewriteRule (.*[^\/])$ page_handler.php?page=$1 [QSA,NC,L]


RewriteRule ^/?$ page_handler.php?page= [L,QSA]
DirectoryIndex page_handler.php?page=

When I put the rule in the current line, it works ok with pages that are supposed to go through the handler BUT it makes existing resources go through it as well (eg domain.com/page_handler.php?page=js/script.js ) which is not good.

When I put it after the other rules it redirects www.domain.com/something to domain.com/?page=something.

So, the question is: how to redirect urls that begin with "www." to the naked (non-www) domains without affecting the other rules?

Thank you!

The problem with your code is that you are applying the first two conditions only to the non-www rule. Conditions can only be tested for the rule that immediately follows them.

So, you'll need to move those down, and clean up a bit:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /page_handler.php?page=$1 [QSA,NC,L]

If this causes issues for you, then you may want to change the way your page is detected, by using the REQUEST_URI instead of a $_GET['page'] . If you want to do this (which is actually a better method), the last rule can be changed to the following:

RewriteRule ^ /page_handler.php [QSA,NC,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM