【问题标题】:trailing slash from URL url for some php url onlyURL url 的尾随斜杠仅适用于某些 php url
【发布时间】:2019-01-24 15:09:32
【问题描述】:

我想将一些带有 .php 的 URL 重写为尾部斜杠 URL。但是,我不想重写所有 URL。

我的代码:

RewriteEngine On
RewriteBase /

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

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


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

我想强制使用斜线:

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

我不需要斜线:

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

【问题讨论】:

  • 您希望/about-us.php 成为about-us.php/ 吗?
  • @starkeen 不想要 /about-us/
  • 所以在浏览器中/about-us.php 应该显示为/about-us/ 但/cart.php 应该显示为/cart or should it just remain /cart.php` ?
  • @anubhava 代码已满,/about-us.php 应显示为 /about-us/ 和 /cart.php 应显示为 /cart.php

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


【解决方案1】:

您可以在站点根目录 .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]

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

【讨论】:

    【解决方案2】:

    您可以使用它从您的 /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]
    

    【讨论】:

    • 我已在我的代码下方添加了您的代码,但没有工作:(
    • 它总是重定向到 /cart/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多