skip to Main Content

I want to rewrite some URLs with .php to trailing slash URLs. However, I don’t want to rewrite all URLs.

My code:

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]

I want force slash on:

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

I don’t need slash on:

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

2

Answers


  1. You can use this to remove the trailing slash from your /cart and /auth URIs .
    Put the following two rules right below RewriteBase line in your htaccess :

    #remove the trailing slash
    RewriteRule ^(cart|auth)/$ $1 [L,R]
    #rewrite /cart and /auth to their original location
    RewriteRule ^(cart|auth)$ $1.php [L]
    
    Login or Signup to reply.
  2. You may use these rules in your site root .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]
    

    Make sure to use only these rules in root .htaccess and test from a new browser or command line curl.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search