URL尾随斜杠仅适用于某些PHP URL

时间:2019-01-23 13:23:29

标签: php apache .htaccess mod-rewrite url-rewriting

我想用var cont = document.getElementById("toast-container"); cont.classList.add("show"); 将某些URL改写为斜杠URL。但是,我不想重写所有URL。

我的代码:

.php

我要强制斜杠:

  • /about-us.php => / about-us /
  • /services.php => / services /

我不需要加斜线:

  • /cart.php => /cart.php
  • /auth.php => /auth.php

2 个答案:

答案 0 :(得分:2)

您可以在网站根.htaccess中使用以下规则:

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+(about-us|services)(?:\.php)?[\s?] [NC]
RewriteRule ^ /%1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_URI} !\.(php?|jpg|gif|png|css|js|html|json|xml|eot|svg|ttf|woff|woff2|zip|csv|xlsx|webp|txt|gz|rar)$ [NC]
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]

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

确保仅在根.htaccess中使用这些规则,并在新的浏览器或命令行curl中进行测试。

答案 1 :(得分:-1)

您可以使用此方法从/cart/auth URI中删除尾部斜杠。 将以下两个规则放在htaccess的RewriteBase行的下方:

#remove the trailing slash
RewriteRule ^(cart|auth)/$ $1 [L,R]
#rewrite /cart and /auth to their original location
RewriteRule ^(cart|auth)$ $1.php [L]