简体   繁体   English

如何为重写规则配置.htaccess文件以摆脱扩展名,尾部斜杠,www?

[英]How to configure .htaccess file for rewrite rules to get rid of extensions, trailing slashes, www?

This is what I want - 这就是我要的 -

When somebody enters site.com/page.php or site.com/page or site.com/page/ , all should work the same, and the url displayed in the address bar should be site.com/page [ I don't like extensions and trailing slashes ] 当有人进入site.com/page.php或site.com/page或site.com/page/时,所有文件都应相同,并且地址栏中显示的网址应为site.com/page [我不知道如扩展名和斜杠]

I also want to get rid of the www from the url bar, as it's unnecessary. 我也想摆脱网址栏中的www,因为这是不必要的。

This is my current .htaccess files Rewrite rules - 这是我当前的.htaccess文件重写规则-

RewriteEngine on
RewriteCond %{HTTP_HOST} ^site\.com
RewriteRule ^(.*)$ http://www.site.com/$1 [R=permanent,L] 

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

This solves the www and the extension issue, but not the trailing slash one! 这样可以解决www和扩展名的问题,但不能解决斜杠!

But, more importantly, I recently installed WordPress at site.com/blog, but whenever I try to access that, I am redirected to the 404 page instead. 但是,更重要的是,我最近在site.com/blog上安装了WordPress,但是每当尝试访问WordPress时,我都会被重定向到404页面。 It works when I remove all the Rewrites! 当我删除所有重写时,它将起作用!

Have I messed up my rewrites? 我搞砸了重写吗? I am not a regular expressions ninja! 我不是正则表达式忍者!

Try adding the following to the top of your existing .htaccess file, above any existing rules eg Wordpress rules. 尝试将以下内容添加到现有.htaccess文件的顶部,在任何现有规则(例如Wordpress规则)上方。

RewriteEngine on
RewriteBase /

#if the host is not site.com, e.g www.site.com
RewriteCond %{HTTP_HOST} !^site\.com$ [NC]
#then redirect to site.com e.g to remove the www
RewriteRule ^(.*)$ http://site.com/$1 [R=301,L] 

#if the URL ends with a slash
RewriteCond %{REQUEST_URI} ^/(.+)/$
#redirect to URL without slash
RewriteRule . http://site.com/%1 [R=301,L] 

#skip wordpress site which starts with blog
RewriteCond %{REQUEST_URI} !^/blog [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

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

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