dsoihsnz85757 2014-10-13 21:57
浏览 35
已采纳

.htaccess中的强制尾随斜线?

Is the below .htaccess code correct? It is used for SEO purposes. I found it in google but I want to be sure it is okay to use. It is placed in .htaccess file and used to force a slash on non-slash URLs. Also, specifically, is the /$1/$2/ part correct?

#Force Trailing Slash
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/$2/ [L,R=301] 

Will I need to also include a RewriteRule for the non-www url (see below) ?

RewriteRule ^(.*)$ http://domain.com/$1/$2/ [L,R=301] 

Also, is it true that you only need to have the below ONCE at the very top of .htaccess?

RewriteEngine On
RewriteBase /

Also, how do you TEST if this code is indeed working? I put the code in my .htaccess file but my homepage does not display a trailing slash.

Edit: Follow-up Question:

Figure A

RewriteRule ^(.*)$ http://www.domain.com/$1/

Does "Figure A" Rewrite Rule only force a trailing slash for

http://www.domain.com/post-one  

Will "Figure A" RewriteRule also force a trailing slash for

http://www.domain.com/category/post-one

If not, how do you add a grouping so that you can do the /$1/$2/ thing?
Would you suggest doing the /$1/$2/ thing (for SEO purposes)? Is there any harm to doing this?

  • 写回答

1条回答 默认 最新

  • douchen2011 2014-10-13 23:07
    关注

    specifically, is the /$1/$2/ part correct?

    No, youre going to get redirected to have 2 trailing slashes because $2 doesn't backreference anything. $1 backreferences the (.*) but you don't have a second grouping. You just need:

    RewriteRule ^(.*)$ /$1/ [L,R=301] 
    

    Will I need to also include a RewriteRule for the non-www url (see below) ?

    No, the 2nd parameter for the RewriteRule directive is the target, so unless you want to redirect people to domain.com instead of www.domain.com you don't need to add anything.

    Also, is it true that you only need to have the below ONCE at the very top of .htaccess?

    Yes

    TO test, just add your htaccess file and go to a URL without a trailing slash. The browser should get redirected and you'll see in the location bar the same URL but with a trailing slash. If that's not what you see, something else is wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址