需要 .htaccess mod 重写帮助


.htaccess mod rewrite help needed

我写了这一小段代码。我对此很陌生,所以我不确定它是否正确。但基本上它允许我使用 PHP 扩展名访问 URL。当人们进入网站时,他们被从地理IP页面重定向到正确的语言,看起来像这样

main.php?lang=uk or nl or en or eu etc

.

现在我也可以这样使用它

main/?lang=uk or nl or en or eu etc

.

我希望能够删除网址 ?lang=uk 中的变量。

我会怎么做。我的.htaccess代码如下

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
DirectorySlash On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]
# remove trailing slash
RewriteRule ^(.*)'/('?.*)?$ $1$2 [R=301,L]
RewriteRule ^(['w'/-]+)('?.*)?$ $1.php$2 [L,T=application/x-httpd-php]

</IfModule>

也感谢任何愿意帮助的人。

RewriteRule 的第一个参数确实匹配域名和前缀*之后以及任何查询字符串(如果存在)之前的任何内容。http://localhost/this/is/my/test?lang=123 this/is/目录中的 .htaccess 文件,它将匹配my/test .若要匹配查询字符串,必须使用 %{QUERY_STRING} 变量。

如果 RewriteRule 的第二个参数(重写的 url)不包含查询字符串,它会自动将原始 url 的查询字符串附加到新 url 中。

在下面的代码中,我使用 %{THE_REQUEST} .这是用于发出页面请求的字符串。它的形式是GET /my/resource?query=string HTTP/1.1.重写内容时它不会改变,这使得防止无限循环很有用。

在您的 php 文件中,确保从 cookie 而不是 get 变量读取语言,然后执行以下操作:

#Set cookie for language
RewriteCond %{QUERY_STRING} ^(.*?)&?lang=([^&]+)&?(.*?)$
RewriteRule ^ %{REQUEST_URI}?%1&%3 [CO=lang:%2:127.0.0.1:1:/:0:1,R,L]
#Remove potential prefix or suffix & from query string
RewriteCond %{QUERY_STRING} ^&(.*?)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*?)&$
RewriteRule ^ %{REQUEST_URI}?%1 [R,L]
#External requests with '.php should be without that.
RewriteCond %{THE_REQUEST} '.php
RewriteRule ^(.*)'.php$ $1 [R=301,L]
#Try to load php page if resource does not alreay have an extension
RewriteCond %{REQUEST_URI} !'.[a-z]+$
RewriteRule ^(.*)$ $1.php [L]