Codeigniter htaccess to remove index.php and www

2020-02-11 08:16发布

I'm trying to get my htaccess rewrite rules to remove the index.php from the url AND also redirect the www. requests to the non-www version.

This is my htaccess which works fine with removing the index.php:

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

And I came across another question on how to remove the www part:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

But I just cant seem to get them to play nicely together! Any advice/suggestions most appreciated!

2条回答
戒情不戒烟
2楼-- · 2020-02-11 09:06

You first need to make sure that the "non-www" rewrite rule comes first and then the one that will redirect all requests to the CodeIgniter bootstrap file. Do note that the following code will honor only HTTP rewrites. If you also need HTTPS it requires some modifications.

RewriteEngine on
# Sending all www requests to the non-www version.
RewriteCond %{HTTP_HOST} ^www.domain.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

# Now the CodeIgniter part
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
查看更多
倾城 Initia
3楼-- · 2020-02-11 09:07
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

RewriteEngine On "starts" rewriting. RewriteCond and RewriteRule work as pairs. Here, we send user to non-www version first, and cleans URLs.

查看更多
登录 后发表回答