【问题标题】:.htaccess won't rewrite correctly.htaccess 不会正确重写
【发布时间】:2016-02-08 18:29:16
【问题描述】:

我的 .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

简而言之,将语言添加到 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 给了我

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

mysite.com/en 给我

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

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

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

【问题讨论】:

    标签: php apache .htaccess


    【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多