如果条件在htaccess文件中写入url重写

时间:2017-07-11 12:50:08

标签: apache mod-rewrite url-rewriting

我的网址重写的htaccess代码如下

RewriteEngine On
RewriteBase "/myekc/"
RewriteCond %{REQUEST_URI} ^/myekc/
RewriteCond %{REQUEST_FILENAME} !/(css|images|js)/ 
RewriteRule "/t/pepsi/(.*)$" "http://192.168.0.175:68/$1" [P]
RewriteRule "^(.*(?:xampp|htdocs)/)(.+)$" "http://192.168.0.179/myekc/t/pepsi/$2" [R,QSA,L]

这适用于1个URI。我现在想写条件,以这种方式写多个uri 例如:

<If "req('uri') == '/t/pepsi/'">
RewriteBase "/myekc/"
RewriteCond %{REQUEST_URI} ^/myekc/
RewriteCond %{REQUEST_FILENAME} !/(css|images|js)/ 
RewriteRule "/t/pepsi/(.*)$" "http://192.168.0.175:68/$1" [P]
RewriteRule "^(.*(?:xampp|htdocs)/)(.+)$" "http://192.168.0.179/myekc/t/pepsi/$2" [R,QSA,L]
</if>
<If "req('uri') == '/t/coke/'">
RewriteBase "/myekc/"
RewriteCond %{REQUEST_URI} ^/myekc/
RewriteCond %{REQUEST_FILENAME} !/(css|images|js)/ 
RewriteRule "/t/coke/(.*)$" "http://192.168.0.175:68/$1" [P]
RewriteRule "^(.*(?:xampp|htdocs)/)(.+)$" "http://192.168.0.179/myekc/t/coke/$2" [R,QSA,L]
</if>

1 个答案:

答案 0 :(得分:0)

您在这里不需要明确的<If>条件。使用mod_rewrite,如果需要将指令应用于其他URL,只需通过指定相应的RewriteRule 模式即可为不同的URL包含该指令。例如:

RewriteEngine On

RewriteRule ^(.*(?:xampp|htdocs)/)(.+)$ http://192.168.0.179/myekc/t/pepsi/$2 [R,L]

RewriteCond %{REQUEST_URI} ^/myekc/
RewriteCond %{REQUEST_FILENAME} !/(css|images|js)/ 
RewriteRule /t/pepsi/(.*)$ http://192.168.0.175:68/$1 [P]

RewriteCond %{REQUEST_URI} ^/myekc/
RewriteCond %{REQUEST_FILENAME} !/(css|images|js)/ 
RewriteRule /t/coke/(.*)$ http://192.168.0.175:68/$1 [P]

请注意,RewriteBase指令只能在.htaccess文件中使用一次(最后一个实例获胜并控制整个文件)。但是你在发布的指令中根本没有使用,所以我暂时将它完全删除了。

然而,目前,这两条规则做同样的事情,所以可以合并:

RewriteCond %{REQUEST_URI} ^/myekc/
RewriteCond %{REQUEST_FILENAME} !/(css|images|js)/ 
RewriteRule /t/(?:pepsi|coke)/(.*)$ http://192.168.0.175:68/$1 [P]
  

我需要条件因为,我想为每个模式设置cookie值。因此,cookie的值将是路径&#34; / t / pepsi /&#34;和&#34; / t /可乐&#34;。如果我一起使用,则考虑最后一个cookie值。示例:要设置Header set Set-Cookie "mycookie=/t/pepsi/" "expr=-z %{req:Cookie}"Header set Set-Cookie "mycookie=/t/coke/" "expr=-z %{req:Cookie}"

你仍然不需要明确的<If>条件,因为mod_rewrite允许你设置cookie,这在这个实例中可能更容易使用(因为你已经在使用mod_rewrite来捕获路径)。例如:

RewriteRule (/t/(?:pepsi|coke)/)(.*)$ http://192.168.0.175:68/$1 [CO=test:$1:.example.com,P]

CO指令上的cookieRewriteRule)标记将Cookie test(在域.example.com上)设置为URL的值 - 请求中的路径(即&#34; / t / pepsi /&#34;或&#34; / t / coke /&#34;)。

参考:
https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_co