.htaccess无法正确重写

时间:2016-02-08 18:29:17

标签: php apache .htaccess

我的.htaccess文件存在一些问题,存储在我网站的根目录。

我想重写以下内容

  1. mysite.com执行mysite.com/index.php?lang=en但重写URL到mysite.com/en /
  2. mysite.com/en(没有尾部斜杠)与上面的内容相同
  3. mysite.com/en/blog/page执行mysite.com/blog/page?lang=en
  4. 简而言之,将语言添加到URL,使用.com,.com / en或.com / en /打开index.php,并删除文件扩展名

    以下是完整的参考文件:

    RewriteEngine on
    
    # Redirect to domain without www.
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule .* http://%1%{REQUEST_URI} [R=301,L]
    # Same for HTTPS:
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]
    
    # Stop hotlinking.
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} ^https?://([^/]+)/ [NC]
    RewriteCond %1#%{HTTP_HOST} !^(.+)#\1$
    RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [NC,F,L]
    
    # Prevent directory listings
    Options All -Indexes
    
    # Request language from URL
    # empty url -> redirect to en/
    RewriteCond %{QUERY_STRING} !lang=(en|de)
    RewriteRule ^$ en/ [R=301,L]
    
    # now all urls have en/ de/ -> parse them
    RewriteRule ^(en|de)/(.*)$  $2?lang=$1&%{query_STRING} [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]
    

    对于完整的披露,它全部来自各种Google结果,我感谢它或许可以做得更好。

    目前,mysite.com给了我

      

    在此服务器上找不到请求的网址/home/towrafvk/public_html/en/.php。

    mysite.com/en给了我

      

    在此服务器上找不到请求的网址/en.php。

    mysite.com/en/和mysite.com/en/blog/page都按预期工作

    我知道问题出现在倒数第三个和倒数第二个重写规则中。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

RewriteEngine on

# Redirect to domain http(s) without www.
RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^ http%2://%1%{REQUEST_URI} [NE,L,R=301]

# Stop hotlinking.
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} ^https?://([^/]+)/ [NC]
RewriteCond %1#%{HTTP_HOST} !^(.+)#\1$
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [NC,F,L]

# Prevent directory listings
Options All -Indexes

# Request language from URL
# empty url -> redirect to en/
RewriteCond %{QUERY_STRING} !lang=(en|de)
RewriteRule ^$ en/ [R=301,L]

# now all urls have en/ de/ -> parse them
RewriteRule ^(en|de)/(.*)$  $2?lang=$1 [L,QSA]

# Use .php file only if not exist without and exist with .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(.+)/?$ $1.php [L]