henrywright
henrywright

Reputation: 10250

How to forbid HTTP access to PHP files?

I'm trying to rewrite URLs using mod_rewrite. This is the rewrite rule in my .htaccess file:

RewriteRule ^([a-z]+)/?$ $1\.php

If the user inputs example.com/contact, the contents of the example.com/contact.php file will load.

The problem is, this leaves me with duplicate content because now both example.com/contact and example.com/contact.php display the same information.

I'd like to forbid access to all PHP files if users attempt to access via HTTP but allow script access (I need my application to work). How can I do this using .htaccess?

Everything I've tried blocks both script and HTTP access. For example, using the following in .htaccess forbids HTTP access but also causes my script to stop working:

Deny from all

Upvotes: 1

Views: 261

Answers (1)

Justin Iurman
Justin Iurman

Reputation: 19026

You can use THE_REQUEST for that.

Your code should look like this now

Options -MultiViews
RewriteEngine On

# if file exists and has ".php" extension then redirect to extensionless equivalent
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} \s/([^/]+)\.php(?:\s|\?) [NC]
RewriteRule ^ /%1? [R=301,L]

# if uri + ".php" exists then internally rewrite to "uri.php"
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)$ /$1.php [L]
  • http://example.com/contact.php will redirect to http://example.com/contact
  • http://example.com/contact will internally rewrite to /contact.php

Upvotes: 1

Related Questions