【发布时间】:2013-11-13 02:46:41
【问题描述】:
您好,我正在努力使用 .htaccess 实现两件事,大概每个问题都相同。
我成功地将一个名为 site-version 的 cookie 设置为 au 或 us。
如果设置了 cookie,我希望 http://www.example.com 和 http://www.example.com/ (内部)重定向到 http://www.example.com/home-au.html(如果 cookie 站点版本=au)。我还想设置一个环境变量 SITE_VERSION=au。
RewriteCond %{HTTP_COOKIE} site-version=(au|us) [NC]
RewriteRule ^/?$ /home-%1.html [NC,QSA,E=SITE_VERSION:%1]
问题似乎是 RewriteRule 上的正则表达式。如果我将它设置为.*,一旦它放弃循环,它似乎会成功设置环境变量,尽管仍然没有重写请求。
如果 URL 是 http://www.example.com/a-specific-page.html 或 http://www.example.com/another-specific-page.html 并且设置了 cookie,我想重定向到 http://www.example.com/a-specific-page-au.html 或 http://www.example.com/another-specific-page-au.html ,即将 -au 附加到文件名。 (并设置环境变量。)
RewriteCond %{THE_REQUEST} ^(a-specific-page|another-specific-page)\.html$ [NC]
RewriteCond %{HTTP_COOKIE} site-version=au [NC]
RewriteRule ^(.*)\.html$ /$1-au.html [QSA,E=SITE_VERSION:au]
稍后在 htaccess 中我再次翻译这些 URL,所以我不想要 L 标志,但是我也尝试过:
RewriteRule ^(.*)\.html$ index.php?q=$1-au.html [QSA,E=SITE_VERSION:au,L]
我在这些主题上尝试了许多细微的变化,没有一个会触发重写。
编辑:我发现我的理解存在根本差距。 URL rewrites trigger another loop 通过.htaccess,所以我需要呈现整个文件而不是片段,这解释了为什么解决方案有效但我仍然没有得到环境变量。
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
########## Set the cookie if the user selects a new country #############
# The webpage submits the existing URL plus the site-version URL parameter. #
# The below strips the parameter and returns to the same URL with a cookie site-version. #
# Unless the site-version is uk (default) in which case the cookie is deleted. #
RewriteCond %{QUERY_STRING} ^.*site-version=(au|us|za|eu)$
RewriteRule (.*) $1? [co=site-version:%1:example.com:1051200:/,R,E=SITE_VERSION:%1,L]
RewriteCond %{QUERY_STRING} ^.*site-version=uk$
RewriteRule (.*) $1? [co=site-version:uk:example.com:-1:/,R,E=SITE_VERSION:uk,L]
#####################
# If the cookie is present and the URL is either a-page.html or another-page.html append -au eg, a-page-au.html #
RewriteCond %{HTTP_COOKIE} site-version=au [NC]
RewriteRule ^(a-page|another-page)\.html$ index.php?q=$1-au.html [NC,QSA,E=SITE_VERSION:au,L]
##########################
# Normal Friendly URLs rewrite, ie, cookie not detected or it isn't one of the listed URLs #
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
【问题讨论】:
-
我测试了第一个 RewriteRule ^/?$ /home-%1.html [NC,QSA,E=SITE_VERSION:%1],内部重定向有效。但这在浏览器的地址框中看不到,因为没有用 R 标志重定向。
-
好的,谢谢,这也是 cookie 行吗?我在浏览器中看到了 cookie,我转到根 URL,有或没有尾随
',我得到了非 au 页面。我想我误解了L标志。我尝试了RewriteRule ^/?$ /home-au.html [NC,QSA,E=SITE_VERSION:au,L],但index.php?q=home-au.html的后续规则仍然被触发(并且看起来没有设置 SITE_VERSION - 我不想担心这个问题,但如果它是诊断性的)。我认为L会阻止任何后续重写。 -
您最好一步完成,直接到 index.php?q=... ?
标签: php .htaccess mod-rewrite cookies