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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记