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

.Htaccess - Remove trailing slash, whilst all pages still go to index.php

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

我想要一个不需要在服务器和本地主机之间 fiddle 的解决方案。

所以 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

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

RewriteEngine on

# removes www. and trailing slash
RewriteCond %{REQUEST_URI} /$ [OR]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*?)/?$ http://%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

试试以下方法:

RewriteEngine on

# Remove the trailing slash, if not in a directory
# DirectorySlash off can be used instead.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ / [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 以使重定向永久化。

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

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]