.htaccess重写以添加国家/地区代码(如果缺少)

时间:2017-05-23 16:01:07

标签: apache .htaccess mod-rewrite

我在子目录/ cms中使用.htaccess文件,并使用此子目录作为RewriteBase。重定向转到'backend.php'并发送我想要的变量。它是一个双语站点(nl | en),荷兰语和英语。只要%{REQUEST_URI}以(nl | en)开头,一切正常。

但是当省略nl | en时我需要回退到默认的荷兰语,但我可以将它添加到以下.htacces文件中。我一直在尝试和搜索,但无法找到正确的语法来实现这一点:

RewriteEngine On
RewriteBase /cms/

RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

RewriteCond %{REQUEST_URI} !(^(nl|en)/)
#RewriteRule (.*) This is where the solution should be used ?

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\.[a-zA-Z]{2,4}$
RewriteRule ^(nl|en)/([^/]+)/$ backend.php?page=$2&language=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\.[a-zA-Z]{2,4}$
RewriteRule (nl|en)(.*)/(\d+)/$ backend.php?page=$2&id=$3&language=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\.[a-zA-Z]{2,4}$
RewriteRule (nl|en)(.*)/(\d+)/(.+)/$ backend.php?page=$2&id=$3&task=$4&language=$1 [QSA,NC,L]

2 个答案:

答案 0 :(得分:0)

您的默认规则可以是以下规则:

# This is where the solution should be used ?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(nl|en)/ [NC]
RewriteRule ^([^/]+)/?$ backend.php?page=$1 [QSA,L]

答案 1 :(得分:0)

处理此问题的一种方法是使用荷兰语语言进行重写。这将默默地改变方向到正确的页面。

RewriteCond %{REQUEST_URI} !^/cms/(?:nl|en)/
RewriteRule ^(.*)$ nl/$1 [L]

如果您希望客户注意并更改网址,则必须执行R|redirect

RewriteCond %{REQUEST_URI} !^/cms/(?:nl|en)/
RewriteRule ^(.*)$ nl/$1 [R,L]