.htaccess 多个URL重写规则(Pretify)

.htaccess 多个URL重写规则(Pretify),.htaccess,mod-rewrite,.htaccess,Mod Rewrite,我有两种类型的URL: http://mydomain.com/npguar/en/products.php http://mydomain.com/npguar/en/1/product_specification.php 早些时候,我使用此.htaccess进行URL重写: RewriteEngine on RewriteCond $1 !^(index\.php|assets|robots\.txt) RewriteRule ^([a-z]{2})/(.*) $2?language=$1

我有两种类型的URL:

http://mydomain.com/npguar/en/products.php

http://mydomain.com/npguar/en/1/product_specification.php

早些时候,我使用此
.htaccess
进行URL重写:

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteRule ^([a-z]{2})/(.*) $2?language=$1 [L]
后来我把它改成这个,但它似乎不起作用

RewriteEngine on

RewriteCond $1 ^(product_specification\.php)
RewriteRule ^([a-z]{2})/([0-9]{1,2})(.*) $3?language=$1&id=$2 [L]

RewriteCond $1 !^(index\.php|assets|robots\.txt|product_specification\.php)
RewriteRule ^([a-z]{2})/(.*) $2?language=$1 [L]

以下是原始规则的工作原理。从URL开始:

http://mydomain.com/npguar/en/index.php?maybe=a-query
仅采用文件系统路径:

npguar/en/index.php
删除用于访问
.htaccess
的前缀:

en/index.php
将其与regex
^([a-z]{2})/(.*)
匹配。它匹配,因此处理将继续。正则表达式中有子模式,它们与URL的以下部分匹配:

(en)/(index.php)
此匹配定义了反向引用
$1=en
$2=index.php

现在检查相应的
RewriteCond
。第一个参数是
$1
,它扩展为字符串
en
。第二个参数是
,以及与该字符串不匹配的正则表达式,因此该条件为true

由于条件为true,请返回
重写规则
,并构造替换字符串
$2?language=$1

index.php?language=en
这是一个内部重定向,所以将原始URL的位重新组合在一起。因为这里有一个查询,并且没有指定
[QSA]
标志,所以替换了原始查询(
maybe=a-query

http://mydomain.com/npguar/index.php?language=en
这个URL从一开始就交还给Apache进行处理。重写规则再次被检查(
[L]
标志不阻止这一点),但它们不匹配,页面被服务


此规则的问题是
RewriteCond
中的
$1
。它应该是
$2
。那么在上面的例子中,
RewriteCond
将为false,但在
en/products.php
中为true

不过,这很好,因为重写cond比您预期的要宽松

新规则不起作用,因为正则表达式分解了这样一个URL(注意第二个
/
的位置):

所以
$1=en
$2=1
$3=/product\u specification.php
。然后将
$1
^product\u specification.php
进行比较,结果不匹配,条件为false

相反,新规则应该是:

RewriteCond $3 ^product_specification\.php$
            ^^                            ^
RewriteRule ^([a-z]{2})/([0-9]{1,2})/(.*) $3?language=$1&id=$2 [L]
                                    ^
(我还在末尾添加了一个
$
,这样
../product\u specification.phpfoo
就不匹配了。)

同样的规则可以是:

RewriteRule ^([a-z]{2})/([0-9]{1,2})/(product_specification\.php)$ $3?language=$1&id=$2 [L]

谢谢,这很有效,但是你能解释一下我的问题到底出了什么问题吗?
RewriteRule ^([a-z]{2})/([0-9]{1,2})/(product_specification\.php)$ $3?language=$1&id=$2 [L]