jeffkee
jeffkee

Reputation: 5238

Need help with .htaccess to hide PHP extension, but with some specific conditions

Here's what I want to achieve:

www.mydomain.com/pages/23/page-title-hash-here -> www.mydomain.com/pages.php/23
www.mydomain.com/[otherpages] -> www.mydomain.com/[otherpages].php
www.mydomain.com/[otherpages]/ -> www.mydomain.com/[otherpages].php

Essentially, there are some simple pages that are queried by just the filename (www.mydomain.com/contact or www.mydomain.com/faq) and then there are pages that I refer to by using the pages.php/23/fdjsoipfahsd or products.php/54/gf-dsdfs-a-f and then I use the $_SERVER['REQUEST_URI'] var to parse through everything after the .php and retrieve the product ID or page ID etc. And there are many variants of these pages..

If I need to hardcode for each .php filename that has trails, I can do that too - we won't be adding any more. However the ones without any trails should still work.

Upvotes: 1

Views: 673

Answers (6)

Ashwini Dhekane
Ashwini Dhekane

Reputation: 2290

RewriteEngine On
RewriteCond $1 !(.*\.php)$
RewriteRule ^/([^/]+)/?$ /$1.php
RewriteCond $1 !(.*\.php)$
RewriteRule ^/([^/]+)/(.+)$ /$1.php/$2 [R=301]

These rules rewrite only if file does not end with .php. Then in second case I set a redirect 301 as in php files you are using .php to get the request part. Without R parameter, the script will not find .php and your request string will be empty and will show default page, if I am correct.

Upvotes: 1

Satya
Satya

Reputation: 3128

Try the below

  1. RewriteRule ^/pages/([^/]+)/([^/]+)/?$ /pages.php/$1
  2. RewriteRule ^/(.*)$ /$1.php
  3. RewriteRule ^/(.*)/$ /$1.php

Upvotes: 1

Alex Emilov
Alex Emilov

Reputation: 1271

Why you don't use just:

RewriteEngine On
Options +MultiViews

If I'm understanding it right, it should work. Try it.

Upvotes: 2

Jeff Parker
Jeff Parker

Reputation: 7517

You could try the following. It ignores requests for files which exists (eg. '/images/image.jpg' would be unaffected), and for ones that don't, it'll attempt to add ".php" to the first 'directory' element, as long as that 'directory' contains only alphanumeric characters.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule  ^/([\w-]*)/?$    /$1.php  [L]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule  ^/([\w-]*)/(.*)$    /$1.php/$2  [L]
  • /test/fred/go -> /test.php/fred/go
  • /images/image.jpg -> /images/image.jpg (assuming this file exists)
  • /script.php/request/thing -> /script.php/request/thing (because the opening 'directory' has a dot in it)
  • /test -> /test.php

Upvotes: 1

Love Sharma
Love Sharma

Reputation: 1999

Try this, which will help you in achieving your requirements:

RewriteEngine on

RewriteCond %{REQUEST_URI} \/(pages|products)\/(.*)
RewriteRule (.*)$ %1.php/%2 [L]

RewriteCond %{REQUEST_URI} \/([a-z]+)([\/]?)
RewriteRule (.*)$ %1.php [L]

Upvotes: 1

Related Questions