1

My directory structure is

- Assets
- Dashboard
   - index.php
   - account.php
index.php
about.php
verify.php

What I basically want it to be:

  1. Remove the .php extension for example http://example.org/about.php should be http://example.org/about/ (including the trailing slash as well)
  2. If .php is encountered in the URL redirect it back to http://example.org/about/

The relevant portions of my .htaccess file looks like this

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

I'm running it on localhost XAMPP web server.

The works fine but when it encounters the trailing slash it gives me a 404.

0
1

Your RewriteRule applied to http://example.org/about/ redirects to http://example.org/var/www/example/public_html/about/.php and result in a 404 Not Found response.

/var/www/example/public_html, or something similar, is the absolute path of the directory that contains the files of the website on the server. This type of path shows up because you did not start the Substitution (in your code: $1.php) with a /, which is mandatory in the .htaccess file in your case (read the 'URL-path' paragraph here).

To achieve your goal, I would use the following Apache httpd directives in the root .htaccess file (I assumed that all your webpages are PHP files):

# Tested with Apache httpd 2.4

### MAP /EXAMPLE/ TO /EXAMPLE.PHP ###
RewriteCond %{REQUEST_URI} /$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+?)/$ /$1.php [END]

### FORCE TRAILING SLASH WHEN ABSENT FOR NON-FILES ###
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) /$1/ [R=301,L]

### REDIRECT (DIR)/INDEX.PHP TO (DIR)/ ###
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (.+/)?index\.php$ /$1 [R=301,L]

### REDIRECT /EXAMPLE.PHP TO /EXAMPLE/ ###
RewriteRule (.+)\.php$ /$1/ [R=301,L]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.