react-router 重定向到 index.html 并从 .htaccess 中的 url 中删除 www

IT技术 .htaccess mod-rewrite reactjs react-router no-www
2021-04-29 02:50:09

我正在用 ReactJS 构建一个小应用程序,所以所有页面都需要提供 index.html 并且 JS 处理 url。这工作正常。但我也想让 .htaccess 从 URL 中删除 www(如果存在)。我正在阅读 mod_rewrite 文档,但我不太清楚如何让它同时做到这两点。

这是我在.htaccess中的代码,请指教!

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(.*) /index.html [NC]
    RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 
</IfModule>
1个回答

回答了我自己的问题

<IfModule mod_rewrite.c>
  RewriteEngine On

  # remove www
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
  RewriteRule ^(.*)$ http://%1/$1 [R=301,L,NE] 

  # redirect all to index
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.html [L,NC]
</IfModule>