使用.htaccess从Apache上的CakePHP 2.x中删除或添加尾部斜杠

Cam*_*ron 5 apache .htaccess cakephp

我正在尝试使用以下.htaccess中的以下内容强制删除或添加尾部斜杠到我的CakePHP 2.x应用程序/app/webroot.

#<IfModule mod_rewrite.c>
#    RewriteEngine On
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_FILENAME} !-f
#    RewriteRule ^ index.php [L]
#</IfModule>


<IfModule mod_rewrite.c>
# Add trailing slash
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|)$
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

或者以下用于添加尾部斜杠.

RewriteCond %{REQUEST_URI} !(/$|\.) 
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]
Run Code Online (Sandbox Code Playgroud)

但我不想强制执行域,因为它可能在本地或在子文件夹中运行.我该如何解决?我在网上看到的所有文档似乎都强制执行应用程序的完整网址.

事实上,即使我使用FULL url它仍然无法正常工作.有没有人设法让这个与CakePHP合作?似乎你必须通过index.php文件运行它

为了澄清我正在寻找一种解决方案,用于在CakePHP中添加和删除尾部斜杠,而无需将URL硬编码到.htaccess文件中.

Jus*_*man 7

这通常不是一件复杂的事情.

那这个呢 ?

<IfModule mod_rewrite.c>
   RewriteEngine On

   # if this is an existing folder/file then leave
   RewriteCond %{REQUEST_FILENAME} -d [OR]
   RewriteCond %{REQUEST_FILENAME} -f
   RewriteRule . - [L]

   # if trailing slash then redirect to url without trailing slash
   RewriteRule ^/?(.+)/$ /$1 [R=301,L]

   # internal rewrite to controller/dispatcher index.php
   RewriteRule ^.*$ /index.php [L,QSA]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

如果这个不起作用,那么这可能是你身边的问题.
你以前用过mod_rewrite吗?它启用了吗?


编辑:如果您的网站不在根文件夹(DOCUMENT_ROOT)中,您有2个选项.您可以将htaccess放在application文件夹或根文件夹中.

我建议你把你的htaccess放在你的application文件夹里(仅限你的网站).否则,代码将不完全相同.这是这种情况下的代码:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /application/

   # if this is an existing folder/file then leave
   RewriteCond %{REQUEST_FILENAME} -d [OR]
   RewriteCond %{REQUEST_FILENAME} -f
   RewriteRule . - [L]

   # if trailing slash then redirect to url without trailing slash
   RewriteRule ^/?(.+)/$ $1 [R=301,L]

   # internal rewrite to controller/dispatcher index.php
   RewriteRule ^.*$ index.php [L,QSA]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

你的第二个问题:

还有什么是ENFORCING尾随斜杠的代码?

您可以使用此代码处理(只更改了一行)

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /application/

   # if this is an existing folder/file then leave
   RewriteCond %{REQUEST_FILENAME} -d [OR]
   RewriteCond %{REQUEST_FILENAME} -f
   RewriteRule . - [L]

   # if no trailing slash then redirect to url with trailing slash
   RewriteRule ^/?(.+)([^/])$ $1$2/ [R=301,L]

   # internal rewrite to controller/dispatcher index.php
   RewriteRule ^.*$ index.php [L,QSA]
</IfModule>
Run Code Online (Sandbox Code Playgroud)