首页 > 解决方案 > htaccess 用最终的子文件夹重写 url

问题描述

我有这样的网址:

https://mywonderfulsite.com/page

我的 .htaccess 将其重写为

https://mywonderfulsite.com/index.php?source=page

.htaccess 如下:

RewriteEngine on
RewriteBase /
RewriteRule \.(php)$ - [L]
RewriteRule ^index\.html$ - [L]
RewriteRule ^favicon\.ico$ - [L]
RewriteRule ^custom404\.html$ - [L]
RewriteRule ^custom500\.html$ - [L]
RewriteRule ^([^/]+)/?$ index.php?source=$1 [L]

如果 url 包含子文件夹,则此操作失败

https://mywonderfuldomain.com/subfolder/anotherpage

那应该变成

https://mywonderfuldomain.com/index.php?source=/subfolder/anotherpage

我似乎不知道如何处理这种情况。如何解决?

标签: apache.htaccessmod-rewriteapache2.4

解决方案


问题在于([^/]+)与除 a 之外的任何内容匹配的模式/

像这样使用它:

RewriteEngine On

RewriteRule \.php$ - [L,NC]

RewriteRule ^(?:favicon\.ico|(?:index|custom500|custom404)\.html)$ - [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .+ index.php?source=$0 [L,QSA]

推荐阅读