哪个mod_rewrite规则可以删除index.php和php扩展(来自另一个现有规则)?

时间:2010-08-03 14:43:04

标签: php .htaccess mod-rewrite

我使用以下模式:

http://example/index.php?lang=en
http://example/index.php?lang=es
http://example/index.php?lang=zh-tw
http://example/index.php?lang=zh-cn

我使用以下mod_write规则:

RewriteEngine on
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA]

根据该规则,我可以使用以下网址将我重定向到上面的网址(原始网址):

http://example/en/index.php
http://example/es/index.php
http://example/zh-cn/index.php
http://example/zh-tw/index.php

我希望我可以输入:

http://example/en
http://example/es
http://example/zh-cn
http://example/zh-tw

访问索引页面......

并输入:

http://example/en/thanks
http://example/es/thanks
http://example/zh-cn/thanks
http://example/zh-tw/thanks

输入我拥有的thanks.php文件。

获得该结果的任何建议?

(我认为这应该很常见。几乎每个专业网站都有这种方式的页面:示例/部分)。

1 个答案:

答案 0 :(得分:1)

如果我理解你正在寻找什么,下面应该做你想要的(我的规则假设你正在使用域的根目录):

RewriteEngine on

# Go to index.php by default if nothing is specified after the language
RewriteCond %{REQUEST_URI} ^/[a-z]{2}(-[A-Za-z]{2})?/?$
RewriteRule ([^/]*)/?$ index.php?lang=$1

# Rewrite domain.com/lang/index to domain.com/lang
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/index(\.php)?$ $1 [R,QSA]

# Allow pages to be specified without the .php extension
# The RewriteCond tells mod_rewrite to not rewrite if the request is a real file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*)(\.php)? $3.php?lang=$1 [L,QSA]

如果您不在域的根目录(即您的网址是domain.com/subdomain/en/index),则需要指定RewriteBase /subdomain并略微修改RewriteCond(您将规则放在子目录中的.htaccess文件中:

RewriteCond %{REQUEST_URI} ^/subdomain/[a-z]{2}(-[A-Za-z]{2})?/?$

如果您仍然无法加载CSS,请尝试使用绝对路径。相对路径将在重定向后应用