重写以添加尾部斜杠,但不依赖于域?(Rewrite to add a trailing slash, but independent of domain?)

我正在使用Apache和mod_rewrite来重写我的网络应用程序的URL。 你可以在这里看到它:

RewriteEngine On RewriteBase / # www. to non-www. RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] # Redirect non-existant files so there's a trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ $1/ [R=301,L] # Send the URL to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php [L,QSA]

一切正常,但问题是尾随斜线重写。 它在我位于域的根目录时有效,但在我的暂存环境中,我在子目录中运行此应用程序。 我必须修改RewriteBase指令以包含子目录或重写失败。

我正在寻找一种解决方案,它将为URL添加一个尾部斜杠 - 无论应用程序是否在服务器的根目录上运行,而无需更改RewriteBase。 提前致谢。

I'm using Apache and mod_rewrite to rewrite URLs for my web app. You can see it here:

RewriteEngine On RewriteBase / # www. to non-www. RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] # Redirect non-existant files so there's a trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ $1/ [R=301,L] # Send the URL to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php [L,QSA]

All working fine, but the problem is the trailing slash rewrite. It works when I'm at the root of the domain, but in my staging environment I'm running this app within a subdirectory. I'm having to modify the RewriteBase directive to include the subdirectory or the rewrite fails.

I'm looking for a solution that will add a trailing slash to the URL - regardless of whether the app is running on the root of the server, without having to change the RewriteBase. Thanks in advance.

最满意答案

经过@MortBM的探索和帮助后 ,看起来效果如下:

RewriteEngine On # www. to non-www. RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] # Add a trailing slash to any non-existent files RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ %{REQUEST_URI}/ [R=301,L] # Send the URI to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php [QSA,L]

总结:删除RewriteBase ,并在重定向中使用%{REQUEST_URI}做了:)

After poking around and some help by @MortBM, looks like the below works well:

RewriteEngine On # www. to non-www. RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] # Add a trailing slash to any non-existent files RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ %{REQUEST_URI}/ [R=301,L] # Send the URI to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php [QSA,L]

Summary: removing the RewriteBase, and using %{REQUEST_URI} within the redirect did it :)

更多推荐