当前位置: 动力学知识库 > 问答 > 编程问答 >

.htaccess - Combine two mod_rewrite rule into one

问题描述:

I need to combine two mod_rewrite rules into one.

1) In CMS, there is index.php that handles all queries on the web. For example if URI is domain.com/query-string, index.php call/include needed parts and displey content. I do this with:

RewriteCond %{REQUEST_URI} !\.[[:alnum:]]+$

RewriteRule ^([^*]+) index.php [L,QSA]

2) I need to redirect with HTTP 301 Moved permanently www to non-www. For example www.domain.com to domain.com. I do this with:

RewriteCond %{HTTP_HOST} ^www.domain.com [NC]

RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

But when I put both these rules into htaccess file, it stops work and all links, that are on the web redirect do index.php and show homepage. That is why, I need to combine these two rules into one.

In the beginning of .htaccess is:

RewriteEngine On

RewriteBase /

Is there any solution, how to do it?

Whole .htaccess:

RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_URI} !\.[[:alnum:]]+$

RewriteRule ^([^*]+) index.php [L,QSA]

RewriteCond %{HTTP_HOST} ^www.domain.com [NC]

RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

I have tried to reorder rules, but with no solution.

Thanks a lot.

网友答案:

This is the correct order. based on the information provided so far I see no reason why this should not work (works here on test machine). If it still does not work -- then maybe there is another rule somewhere else (or redirect is made in your PHP app).

RewriteEngine On
RewriteBase /

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

RewriteCond %{REQUEST_URI} !\.[[:alnum:]]+$
RewriteRule ^([^*]+) index.php [L,QSA]

BTW, if you matching %{HTTP_HOST} with regular expression (pattern starts with ^) then it's better to escape dots, as in some circumstances it can make huge difference (maybe not in your case, but still, since dot means "any character") -- ^www\.domain\.com. Alternatively use plain string comparison instead of regex: =www.domain.com

分享给朋友:
您可能感兴趣的文章:
随机阅读: