guru38
guru38

Reputation: 63

.htaccess Conflict: How can I remove .php AND rewrite URLs?

Here's my situation: I have a directory which I need to rewrite URLs in, so that ?page=hello can be accessed at either /hello or /hello/. I then have a sub-directory which needs .php extensions to be internally appended, so /subdir/example.php can be accessed at /subdir/example and /subdir/example/.

I developed the two parts of the site independently, and I'm now having trouble getting htaccess to meet both requirements.

My current .htaccess file is:

RewriteEngine On

# The root directory bit...
Redirect 301 /home /
RewriteEngine On
RewriteCond %{REQUEST_URI} !/subdir
RewriteRule ^([A-Za-z0-9-_/]+)/?$ index.php?page=$1 [L]

# Remove .php
RewriteEngine On
RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

The rules work perfectly independently, ie if I remove the other one, but, together, does append.php but the rewrite rule fails.

I've tried making two separate htaccess files, one for the subdir and one for the root dir, with the appropriate rule (nice URL rule for root dir and remove .php for subdir), but this just means that appending .php no longer works.

Does anyone have any solutions to this?- or any resources to point me in the right direction? I'm currently in a hole of PHP and Apache documentation!

Upvotes: 0

Views: 62

Answers (1)

guru38
guru38

Reputation: 63

This is what worked:

RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(subdir/.*?)/?$ $1.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?page=$1 [QSA,L]

This does only remove .php for files of the subdirectory, but is certainly better than nothing.

Upvotes: 1

Related Questions