0

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!

guru38
  • 63
  • 5
  • I would recommend looking into using the [front controller pattern](https://stackoverflow.com/questions/6890200/what-is-a-front-controller-and-how-is-it-implemented) and a [router](https://packagist.org/?query=router). Then you can put all the URL logic in the application itself (usually much easier than messing with rewrite rules) and also make it much easier to port to other web servers (that doesn't read htaccess files). – M. Eriksson Dec 12 '21 at 13:43
  • @M.Eriksson Thank you!- I did wonder how WordPress and the likes did rewrite rules in the way that they do. I'll have a look into this now, and hopefully it'll work in conjunction with the removal of `.php`. – guru38 Dec 12 '21 at 13:48

1 Answers1

1

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.

guru38
  • 63
  • 5
  • "This does only remove .php for" - This doesn't "remove" anything. It enables URLs to resolve that have _already_ had the `.php` file extension removed. The first rule does the opposite of what is stated and internally _appends_ the `.php` extension. – MrWhite Dec 12 '21 at 18:42
  • @MrWhite Apologies for the confusion. I did mean *internally append*, I just worded it as *"optionally remove(d)"*. I've updated the question to better reflect what I meant. – guru38 Dec 12 '21 at 19:43