.Htaccess - 删除尾部斜杠,而所有页面仍然转到index.php

时间:2015-02-15 12:30:37

标签: apache .htaccess mod-rewrite

我搜索了之前提出的问题,但没有一个问题和我一样。我想要删除尾部斜杠,同时仍然将所有页面发送到index.php(或者如果文件实际存在,请使用它。)

我想要一个解决方案,我不必在服务器和localhost之间进行操作。

所以localhost/pages/to/file/http://example.com/pages/to/file/,转到... /pages/to/file

我当前的htaccess文件:

RewriteEngine on

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

# if file exists, ignore the index.php re-write
RewriteCond %{REQUEST_FILENAME} !-f

# send everything to index.php
RewriteRule . index.php

3 个答案:

答案 0 :(得分:0)

您可以在现有规则中添加额外条件,以删除www并删除该规则中的任何尾部斜杠。

RewriteEngine on

# removes www. and trailing slash
RewriteCond %{REQUEST_URI} /$ [OR]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*?)/?$ http://%1/$1 [R=301,QSA,NC,L]

# if file exists, ignore the index.php re-write
RewriteCond %{REQUEST_FILENAME} !-f

# send everything to index.php
RewriteRule . index.php

有关说明,请参阅the documentation

答案 1 :(得分:0)

尝试以下内容:

RewriteEngine on

# Remove the trailing slash, if not in a directory
# DirectorySlash off can be used instead.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Remove www. (generic method with HTTPS support)
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R,L]

# Send everything (except existing files) to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

如果此方法适用,请将R标记更改为R=301以使重定向永久化。

答案 2 :(得分:0)

有一个单独的规则来删除尾部斜杠:

RewriteEngine on

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?\s]
RewriteRule [^/]$ %{REQUEST_URI}/ [L,NE,R=301]

# if file/directory exists, ignore the index.php re-write
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# send everything to index.php
RewriteRule . index.php [L]