.htaccess regular expression issue

妖精的绣舞 提交于 2020-01-03 05:58:13

问题


I still have no answer about this so I'm posting it here.

I want to match an url in the form of root/language/sub/.../document in a .htaccess file and then rewrite it as root/sub/.../document.php?lang=language

Im close to hit but it seems my regexp doesn't 'catch' the input url. Here it is :

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond ^[a-z]{2}.*$/%{REQUEST_FILENAME}\.php -f
RewriteRule ^([a-z]{2})/(.*)$ $2.php?lang=$1

Can someone point me out what is wrong here ? I'm no expert in regexp nor apache rewrites.

Tyvm

* EDIT *

root stands for domain ie mydomain.net

Here are a few examples :

mydomain.net/fr/contact

should be rewriten to

mydomain.net/contact.php?lang=fr

and

mydomain.net/en/articles/view

should be rewriten

mydomain.net/articles/view.php?lang=en

etc...


回答1:


I believe you are looking for this configuration:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} ^(.*/|)(en|de|fr)/(.*)$ [NC]
RewriteCond %1%3.php -f
RewriteRule ^(.*/|)(en|de|fr)/(.*)$ $1$3.php?lang=$2 [NC,QSA,L]

Explanation:

RewriteCond %{REQUEST_FILENAME} !-d

Checks if requested url is not a directory. If yes, no rewriting will be processed.

RewriteCond %{REQUEST_FILENAME} ^(.*/|)(en|de|fr)/(.*)$ [NC]

Checks if url contains /xx/ part inside, where xx is one en, de or fr. Flag [NC] allows uppercase and lowercase charactes, so for example EN or Fr will be accepted. If there is no such "language" part in the url, no rewriting will be processed.

RewriteCond %1%3.php -f

Checks if %1%3.php file exists, where %1 is (.*/|) and %3 is (.*) matches from the previous RewriteCond ^(.*/|)(en|de|fr)/(.*)$. If such php file does not exist, no rewriting will be processed.

RewriteRule ^(.*/|)(en|de|fr)/(.*)$ $1$3.php?lang=$2 [NC,QSA,L]

In the RewriteRule left condition will be matched if it came to this line, as it was already checked with RewriteCond, so now it will process rewriting to php file, adding lang part, but because there is also [QSA] flag, it will keep also other GET parameters, so lang will be added to existing parameters. Flag [L] says it is last rewriting rule that should apply and no more rewriting will be processed with this url.




回答2:


Well I'm not sure what root is doing in there, have you tried

RewriteRule ^root/([a-z]{2})/(.*)$ root/$2.php?lang=$1



回答3:


What's wrong is the second RewriteCond. But your question is vague. If you mean you're trying to convert

root/foo/sub/.../something.php

to

root/sub/.../something.php?lang=foo

then start fidgeting with this:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^root/([^/]+)/sub/(.*)/%{REQUEST_FILENAME}$ root/sub/$2/%{REQUEST_FILENAME}?lang=$1


来源:https://stackoverflow.com/questions/12327059/htaccess-regular-expression-issue

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