首页 > 解决方案 > Laravel 将 www 重定向到非 www 且 htaccess 无法正常工作

问题描述

.htaccess我在将 www URL 重定向到非 www URL的文件中有以下行:

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

尝试加载 index route: https://www.example.comto时它可以正常工作https://example.com,但是如果有人尝试加载任何其他路由,它不会加载任何内容,例如,如果我尝试加载https://www.example.com/about-us它将 URL 转换为https://example.com/index.php并且它不会加载任何内容。

我怎样才能解决这个问题?

编辑

我的完整.htaccess如下:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On
  
  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    
    RewriteCond %{REQUEST_URI} !(\.css|\.pdf|\.mp4|\.woff|\.woff2|\.ttf|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(css|js|images|favicon|fonts|font|videos|storage|pdf)/(.*)$ public/$1/$2 [L,NC]
    
    
  
    
</IfModule>

<IfModule mod_headers.c>
   Header set Access-Control-Allow-Origin "*"
</IfModule>
<FilesMatch ".(eot|ttf|otf|woff|woff2)">
   Header set Access-Control-Allow-Origin "*"
</FilesMatch>


<Files .env>
order allow,deny
Deny from all
</Files>

标签: apache.htaccessmod-rewrite

解决方案


你可以试试这个

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]

推荐阅读