如何使用htaccess&apache重写/ page到/ xx / page?

您好我已经find了许多mod-rewrite和Apache的资源,但我还没有成功的做一个工作的例子。

下面的例子适用于

✓WORKS example.com/en/page1.php☞example.com/page1.php?ln=en (内部redirect

✓WORKS example.com/page1.php☞example.com/en/page1.php (redirect)

✓WORKS example.com/en/☞example.com/index.php?ln=en (内部redirect)

✓WORKS example.com/☞example.com/en/ (redirect)

✓WORKS example.com/blahblah☞example.com/en/error.php (redirect)

✓WORKS example.com/zh/blahblah☞example.com/zh/error.php (redirect)

✖FAILS example.com/de☞example.com/en/error.php (redirect – 应该是example.com/de/

✖失败example.com/de/blahblah☞example.com/en/error.php (redirect – 应该是example.com/de/error.php

<IfModule mod_rewrite.c> RewriteEngine On DirectorySlash On # Force hostname without www REDIRECT RewriteCond %{HTTP_HOST} !^example\.com [NC] RewriteCond %{HTTP_HOST} !^$ RewriteRule ^(.*)$ http://%1/$1 [R=301] # /xx/somepage.php -> /somepage.php?ln=xx INTERNAL REWRITE RewriteCond %{REQUEST_URI} ^/../.+ [NC] RewriteRule ^(en|de)/(.*) $2?ln=$1&%{QUERY_STRING} [L] # /en -> /en/ REDIRECT RewriteCond %{REQUEST_URI} ^/..$ [NC] RewriteRule ^(.*)$ $1/ [R=302,L] # /somepage.php -> /en/somepage.php REDIRECT RewriteCond %{REQUEST_URI} !^/../ [NC] RewriteCond %{ENV:REDIRECT_STATUS} !=200 RewriteRule ^(.*)$ /en%{REQUEST_URI} [R=302,L] # /en/ -> /en/index.php INTERNAL REWRITE RewriteCond %{REQUEST_URI} !^/../.+ [NC] RewriteCond %{ENV:REDIRECT_STATUS} !=200 RewriteRule ^(.*)$ /$1index.php [L] </IfModule> 

★注1: R=302用于debugging。 在服务器上它实际上是R=301

★注2:它在Apache 2.2上,所以%{ENV:REDIRECT_STATUS} !=200位试图模拟后面的Apache 3.2.9的[END]标志。

谢谢!

★编辑:这里是更多的.conf文件

 <Directory /var/www/vhosts/example.com/httpdocs> Options +FollowSymLinks -Indexes AllowOverride All AddDefaultCharset utf-8 ErrorDocument 400 /error.php ErrorDocument 401 /error.php ErrorDocument 402 /error.php ... ErrorDocument 500 /error.php [above code here] </Directory> 

如果可以在RewriteRule指定匹配,则不必指定RewriteCond 。 例如:

  # /xx/somepage.php -> /somepage.php?ln=xx INTERNAL REWRITE RewriteCond %{REQUEST_URI} ^/../.+ [NC] RewriteRule ^(en|de)/(.*) $2?ln=$1&%{QUERY_STRING} [L] 

应该只是:

  # /xx/somepage.php -> /somepage.php?ln=xx INTERNAL REWRITE RewriteRule ^(en|de)/(.*) $2?ln=$1&%{QUERY_STRING} [L] 

遍历两个不起作用的URL:

example.com/de

  1. 匹配用# /en -> /en/ REDIRECT注释重写,URI变成/de/
  2. 不符合任何其他规则。 你期望它符合最后两条规则吗? 他们不会因为%{ENV:REDIRECT_STATUS} != 200

访问example.com/de/是否直接与上述URL有不同的结果?

example.com/de/blahblah

  1. 匹配用# /xx/somepage.php -> /somepage.php?ln=xx注释重写,URI成为blahblah.php?ln=de&othergetvars
  2. 没有别的匹配

你能向我们展示configuration虚拟目录的指令吗?