mod_rewrite : if / else type RewriteRule

会有一股神秘感。 提交于 2019-12-12 09:47:33

问题


The following rewrite passes a string starting with the number 4 as a variable to process.php :

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(4[^/]*)$ /process.php?variable=$1 [L]

So this

http://www.domain.com/4shopping

is mapped to

http://www.domain.com/process.php?variable=4shopping

But I want to extend this last rewrite rule to basically state:

if word begins with 4, map to /process.php?variable=$1
else map to /index.php

The second (else) part of this statement is the basic WordPress rewrite rule. So for example:

http://www.domain.com/shopping

which has no 4 will be directed to

http://www.domain.com/index.php?shopping (I believe this is how WordPress permalinks work!)

回答1:


Try this:

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^(4[^/]*)$ process.php?variable=$1 [L]
RewriteRule ^([^4/][^/]*)$ index.php?$1 [L]

The first rule will catch any request that can be mapped to an existing file or directory and will end the rewrite process. The second rule is yours (without the RewriteCond conditions). And the third rule will catch any request that’s URL path does not start with the number 4.




回答2:


Here's the solution:

RewriteRule ^(4[^/]*)$ /feedback.php?sms_code=$1 [L]
#
# BEGIN wordpress
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END wordpress

I left the default Wordpress rules in place, and added my own conditional rule above, making sure to terminate [L] processing if the condition was met




回答3:


I would add two lines to the end of what you already have. The additional rules will convert to index.php anything that hasn't already been converted to process.php.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(4[^/]*)$ /process.php?variable=$1 [L]

RewriteCond %{SCRIPT_FILENAME} !process\.php
RewriteRule ^([^/]*)$ index.php?$1


来源:https://stackoverflow.com/questions/1478993/mod-rewrite-if-else-type-rewriterule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!