2

I want to run my PHP web pages on an apache web server without the .php extension. So I added the following code:

RewriteEngine on
RewriteBase /
Rewritecond %{REQUEST_URI} !(^/?.*\..*$) [NC]
RewriteRule (.*)$ $1.php [NC]

in the .htaccess file. This solves my problem but another problem arises. I cannot view the content of any directory (i.e. the file contained in the directory). Please provide me an alternate RewriteRule without this problem.

ata
  • 3,398
  • 5
  • 20
  • 31

3 Answers3

4

You need to make sure that the request URI points to an existing resource if you append the.php to the end of it:

RewriteEngine on
RewriteBase /
Rewritecond %{REQUEST_URI} !(^/?.*\..*$) [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*)$ $1.php [NC]

the line RewriteCond %{REQUEST_FILENAME}.php -f checks if a ".php" is appended to the requested URI, it mapes to an existing file (-f).

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
3

You can use this code, it is working on my website:

RewriteEngine On
#unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

#redirect external .php requests to extensionless url
#RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
#RewriteRule ^(([^/]+/)*[^.]+)\.php $1 [R=301,L]
1

Try setting DirectoryIndex above your RewriteCond:

DirectoryIndex index.php
buley
  • 28,032
  • 17
  • 85
  • 106