Michelle
Michelle

Reputation: 570

Use htaccess to remove trailing slashes, index.php, and still use relative paths

I am trying to write an .htaccess file that accomplishes the following goals:

Some example URLS (display URL = actual location):

And here's what I have so far in the folder ABOVE admin. It removes the php extension while allowing me to access any existing files, but it also strips everything after .php and doesn't remove trailing slashes.

RewriteEngine On

# Redirect php filename externally
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,QSA]
# change 302 to 301 on live for perm redirect

# Redirect php filename internally
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L,QSA]

# Rewrite Admin URLS (after specififcally looking for files)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule admin/. admin/index.php [L,QSA]
# index.php looks at $_SERVER['REQUEST_URI'] to decide what to do next

# No Directory Listings
Options -Indexes

My biggest concern is being able to include files (.php, .inc, .css, .js) with relative paths and not having to use absolute paths if I can help it.

Upvotes: 0

Views: 3279

Answers (1)

Paul Redmond
Paul Redmond

Reputation: 693

I generally prefer to go with a framework that provides routing capabilities instead of the nightmare of all those Rewrite rules for folders/files. There are a slew of PHP frameworks that support this easily, such as Silex, Symfony, or Laravel, to name a few.

Another reason that doing the routing in the application is easier, is that it abstracts application routing from the webserver for the most part. For example, if you move to Nginx, you will have to refactor all of the above.

My .htaccess might look something like the following:

<IfModule mod_rewrite.c>
    RewriteEngine On
    # Redirect to non-trailing slash
    RewriteRule ^(.*)/$ /$1 [R=301,L]
    # Block access to "hidden" directories whose names begin with a period.
    RewriteRule "(^|/)\." - [F]
    RewriteBase    /
    # Redirect requests that have no real file
    RewriteCond    %{REQUEST_FILENAME}  !-f
    RewriteRule    (.*)  index.php    [QSA,L]
</IfModule>

Upvotes: 0

Related Questions