用于管理语言重定向的Apache重写规则

时间:2015-09-17 13:06:36

标签: regex apache .htaccess mod-rewrite redirect

我正在尝试构建一个重写规则来实现基于语言的重定向。

我的目录结构如下:

.
├── .htaccess
├── assets
│   ├── css
│   │   └── master.min.css
│   ├── fonts
│   │   ├── fontawesome-webfont.eot
│   │   ├── fontawesome-webfont.svg
│   │   ├── fontawesome-webfont.ttf
│   │   ├── fontawesome-webfont.woff
│   │   ├── fontawesome-webfont.woff2
│   │   └── FontAwesome.otf
│   ├── img
│   │   ├── logo.svg
│   │   ├── slide1.jpg
│   │   ├── slide2.jpg
│   │   ├── slide3.jpg
│   │   └── slide4.jpg
│   └── js
│       └── scripts.min.css
├── de
│   ├── index.php
│   ├── sie.php
│   ├── uns.php
│   └── zusammen.php
├── en
│   ├── index.php
│   ├── together.php
│   ├── us.php
│   └── you.php
├── fr
│   ├── ensemble.php
│   ├── index.php
│   ├── nous.php
│   └── vous.php
└── it
    ├── index.php
    ├── insieme.php
    ├── noi.php
    └── voi.php

我没有root index.html或index.php文件。我想让.htaccess通过嗅探浏览器语言将用户重定向到语言目录中的一个索引文件,然后将用户重定向到适当的语言。当浏览器的语言无法被嗅探时,默认语言应该是法语。

我当前的.htaccess文件包含以下内容:

Options -Indexes +FollowSymLinks

RewriteEngine On

RewriteRule ^(en|de|fr|it)/ - [L,NC]

RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule ^(.*)$ /fr/$1 [L]

RewriteRule ^(.*)$ /en/$1 [L]
RewriteRule ^(.*)$ /de/$1 [L]
RewriteRule ^(.*)$ /it/$1 [L]

这似乎部分起作用,但它无法访问各种资产,如图像,javascripts或字体。

一旦页面加载,此后,导航和更改语言不会有任何问题,因为我使用的内部URL直接链接到相应目录中的特定页面。

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用浏览器的语言进行检测和路由。将此代码放在root .htaccess

RewriteEngine On

RewriteRule ^(assets|en|de|fr|it)/ - [L,NC]

# detect browser language and capture first 2 chars
RewriteCond %{HTTP:Accept-Language} ^([a-z]{2}) [NC]
# current request is not pointing to a real file
RewriteCond %{REQUEST_FILENAME} !-f
# check if corresponding directory exists
RewriteCond %{DOCUMENT_ROOT}/%1/ -d
RewriteRule ^ %1%{REQUEST_URI} [L]

## default fr rule
# current request is not pointing to a real file
RewriteCond %{REQUEST_FILENAME} !-f
# current request is not pointing to a real directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^[^/]+/?$ fr%{REQUEST_URI} [L]

答案 1 :(得分:0)

我不知道你如何尝试在你的源代码中包含资产,所以你可以试试这个:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/(img|css|js|fonts)/(.*)$ assets/$2/$3 [QSA,L]
RewriteRule ^(.*)/(fr|it|en|de)/(.*)$ $2/index.php?area=$3   [QSA,L]
RewriteRule ^.htaccess$ - [F]