简体   繁体   中英

.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 optionally removed, 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, do remove.php but the rewrite rule fails.

I've tried making two seperate 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 removing.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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM