简体   繁体   中英

Remove .php extension, force non-slash, force non-www, force https with .htaccess

I have been looking into this for quite a while now, but i just can't get it right. When I have one part working (eg forcing non-php), the other part stops working (eg forcing non-slash).

What I want exactly:

  1. remove .php extension (so example.com/foo.php becomes example.com/foo in the browser url bar)
  2. remove the slash at the end of a URL (so example.com/foo.php/ becomes example.com/foo . BUT when it's a directory with an index.php inside, it has to redirect accordingly (i can't get this last part to work)
  3. force non-www (this works)
  4. force https (this works)

What I my .htaccess looks like right now:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ /$1 [R=301,NE,L]

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

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

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off  
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

I experience the following problems with this:

  1. example.com/foo.php/ redirects to example.com/foo.php instead of example.com/foo

  2. example.com/foo.php/foo displays the example.com/foo.php file, while example.com/foo/foo displays a 404 message (the latter would be correct in my case)

  3. example.com/admin (this is a folder with an index.php in it) displays a 404 message

I appreciate your help!

Okay, so I know it is a broad question. But if anyone ever searches for this, I almost have it (the only thing that doesn't work is redirecting domain.com/foo.php/foo to domain.com/foo/foo

Here is the .htaccess file I have right now:

RewriteEngine On

Options -Indexes

RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /([^/]+)\.php(\?|\ |$)
RewriteRule ^ /%2 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ /$1 [R=301,NE,L]

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

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

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off  
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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