简体   繁体   English

如何使用htaccess删除URL中的最后一个斜杠?

[英]How to remove the last slash in an URL with htaccess?

I'm trying to remove the last slash of my URLs. 我正在尝试删除网址的最后一个斜杠。

I put this in my htaccess file : 我把它放在我的htaccess文件中:

RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]

It works with files hosted in the root (or pages generated from the database), but it doesn't work with files hosted in subdirectories. 它适用于根目录中托管的文件(或从数据库生成的页面),但不适用于子目录中托管的文件。

For example, I would like that this : 例如,我想要这样:

 http://mywebsite.com/dir1/dir2/dir3/index.php

goes to that : 转到:

 http://mywebsite.com/dir1/dir2/dir3

but it goes to that : 但它涉及到:

 http://mywebsite.com/[homeserver]/[server]/www/dir1/dir2/dir3

What is wrong with my htaccess file ? 我的htaccess文件怎么了?

Edit : here is the entire htaccess file 编辑:这是整个htaccess文件

SetEnv PHP_VER 5
SetEnv REGISTER_GLOBALS 0
Options +FollowSymLinks

RewriteEngine on
RewriteBase /

RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]

### Remove www
RewriteCond %{HTTP_HOST} !^mywebsite\.com$ [NC]
RewriteRule ^(.*)$ http://mywebsite.com/$1 [R=301,L]

### Get the URL in pathinfo mode
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php/$1

### Redirect index.php to the root
RewriteRule ^index\.php$ http://mywebsite.com/ [R=301,L]

尝试在RewriteEngine On之后添加以下添加规则,并提供完整的.htaccess进行进一步分析。

RewriteBase /

Have it like this: 像这样:

SetEnv PHP_VER 5
SetEnv REGISTER_GLOBALS 0
Options +FollowSymLinks

RewriteEngine on
RewriteBase /

### Remove www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L,NE]

## Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [NE,R=301,L]

### Redirect index.php from anywhere
# remove index.php
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.php$ [NC]
RewriteRule ^ %1 [L,R=301,NE]

### Get the URL in pathinfo mode
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [L]

Make sure to clear your browser cache before testing this change. 在测试此更改之前,请确保清除浏览器缓存。

You can use below code in .htacccess file to remove slash at the end of URL. 您可以在.htacccess文件中使用以下代码来删除URL末尾的斜杠。

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

I have used this and working fine. 我已经用过并且工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM