[英]PHP .htaccess removing .php extension and language directory to parameter
I'm looking for a regulair expression for a .htaccess
file inside my PHP server. 我正在寻找PHP服务器中.htaccess
文件的regulair表达式。
What I want is that it detects the language from the first directory as parameter: 我想要的是它从第一个目录中检测语言作为参数:
Any other options must be treated as a directory or filename. 任何其他选项都必须视为目录或文件名。 The language must be given as parameter without corrupting any other parameters. 语言必须作为参数提供,而不会破坏任何其他参数。
Also I want the last /
replaced by .php
. 我也想最后/
替换为.php
。
Some examples: 一些例子:
host.com/nl/index/ -> host.com/index.php?lang=nl
host.com/de/test/abc/ -> host.com/test/abc.php?lang=de
host.com/be/a/b/c/?t=23 -> host.com/a/b/c.php?lang=be&t=23
Is this possible? 这可能吗? I can't get it to work, I hope someone will help me out! 我无法正常工作,希望有人能帮助我!
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule >>> requested expression and replacing pattern <<<
</IfModule>
RewriteRule ^/([a-z]{2})(/.+)/?$ $2.php?lang=$1 [QSA]
Regexes are easiest to interpret by considering a piece at a time. 通过一次考虑正则表达式,最容易解释正则表达式。 Let's break that down: 让我们分解一下:
^
- start of URL ^
-URL的开头 /
- match first slash /
-匹配第一个斜杠 ([az]{2})
- match and capture 2 letters (goes into the $1
variable) ([az]{2})
-匹配并捕获2个字母(进入$1
变量) (
- begin capture group (goes into $2
) (
-开始捕获组(进入$2
) /
- match a slash /
-匹配一个斜杠 .+
- match zero or more characters .+
-匹配零个或多个字符 )
- end capture group ( $2
) )
-结束捕获组( $2
) /?
- match an OPTIONAL end slash of the "file path" (but don't capture it) -匹配“文件路径”的可选斜杠(但不要捕获) $
- end of URL $
-网址结尾 So, you're capturing two things: 因此,您要捕获两件事:
1 . 1 。 the language (capture group $1
): 语言 (捕获组$1
):
([a-z]{2})
2 . 2 。 the file path , starting with a slash (capture group $2
), followed by an optional slash: 文件路径 ,以斜杠(捕获组$2
)开头,后跟可选的斜杠:
(/.+)/?
Finally, the QSA
flag at the end appends your original query string (if there was one) to your rewritten URL. 最后,最后的QSA
标志会将原始查询字符串(如果有的话)附加到重写的URL上。 If you'd like to make your regex match case-insensitive (ie allow URLs like host.com/NL/index/
), you can add the NC
flag too: [QSA,NC]
. 如果您想使正则表达式不区分大小写(即允许使用host.com/NL/index/
URL),则也可以添加NC
标志: [QSA,NC]
。 Alternatively, you could explicitly allow capital letters by using [A-Za-z]
instead of [az]
in your regex. 另外,您可以通过在正则表达式中使用[A-Za-z]
而不是[az]
来明确允许使用大写字母。
尝试这个
RewriteRule ^([a-z]{2})/(.+)/?$ /$2.php?lang=$1 [QSA]
Enable mod_rewrite and .htaccess through httpd.conf
and then put this code in your .htaccess
under DOCUMENT_ROOT
directory: 通过httpd.conf
启用mod_rewrite和.htaccess,然后将此代码放在DOCUMENT_ROOT
目录下的.htaccess
:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$2.php -f
RewriteRule ^([a-z]{2})/(.+?)/?$ /$2.php?lang=$1 [L,QSA,NC]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.