简体   繁体   English

apache重定向到裸(非www)域使页面处理程序混乱

[英]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 ). 我网站上的所有网址实际上都经过一个由page GET参数处理的PHP页面(即domain.com/sub/test实际上是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. 我一直试图将所有www.domain.com请求重定向到domain.com以改善SEO等。

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: 这是.htacess文件:

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. 当我将规则放在当前行中时,它可以处理应该通过处理程序的页面,但它也可以使现有资源也可以通过(例如domain.com/page_handler.php?page=js/script.js ),这不好。

When I put it after the other rules it redirects www.domain.com/something to domain.com/?page=something. 当我将其放在其他规则之后时,它会将www.domain.com/something重定向到domain.com/?page=something。

So, the question is: how to redirect urls that begin with "www." 因此,问题是:如何重定向以“ www”开头的网址。 to the naked (non-www) domains without affecting the other rules? 裸域(非www)域,而不影响其他规则?

Thank you! 谢谢!

The problem with your code is that you are applying the first two conditions only to the non-www rule. 您的代码的问题在于,您仅将前两个条件应用于非www规则。 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'] . 如果这导致了你的问题,那么你可能想改变你的方式page检测,通过使用REQUEST_URI代替$_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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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