duanputian5341 2017-04-05 22:31
浏览 53
已采纳

.htaccess - 删除www,强制https,删除php并删除尾部斜杠

I am trying to archieve the following with least amount of redirects;

  • Remove WWW
  • Force HTTPS
  • Remove php extension
  • Remove end trailing slash

What i have so far and is working:

RewriteEngine On

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

# FORCE HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# REMOVE TRAILING SLASH
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# REMOVE PHP EXTENSION
RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/?$ /$1.php [END]

Current behaviour:

http://www.example.com/functions.php -> https://example.com/functions

(works with 4 redirects)

OR

http://www.example.com/functions/ -> https://example.com/functions

(works with 4 redirects)

Does anyone have any suggestions how to make this work with fewest possible redirects?

  • 写回答

1条回答 默认 最新

  • dongshun7312 2017-04-05 23:02
    关注

    It doesn't hurt to just always rewrite to https and lose the www in one step. Trailing slash is unchanged, but lost a line on removing php-extenstion by inverting the Cond.

    # REMOVE WWW & FORCE HTTPS
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR]
    RewriteCond %{https} off
    RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]
    
    # REMOVE TRAILING SLASH
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301] 
    
    # REMOVE PHP EXTENSION if there's no file with this name
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301]
    

    If you also need handling for files that were requested as file/ without .php, you should stay with your code for the final part:

    RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301]
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+)/?$ /$1.php [END]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电脑出问题了,说是usbmom注册表没
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网