Search code examples
php.htaccessurlmod-rewriteforwarding

mod_rewrite conditions in apache to remove .php not working as expected


RewriteEngine On

RewriteRule ^/showlisting/(.*)$ showlisting.php/$1 [L]
RewriteRule ^/listings/(.*)$ listings.php/$1 [L]

RewriteCond %{HTTP_HOST} ^mydomain\.
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]

ErrorDocument 404 /notfound

In the above, this is what I want to achieve:

  1. I want to forward any URLs such as www.mydomain.com/showlisting/my-listing-data/with-more-slashes/and-some-text to show the content of www.mydomain.com/showlisting*.php*/my-listing-data/with-more-slashes/and-some-text but with URL masking so that the .php does NOT appear on the browser window.
  2. I also want to append with www when the www is not present in the request for SEO purposes, although I'm not sure how important this is these days.

When I visit www.mydomain.com/showlisting/my-listing-data/with-more-slashes/and-some-text however it shows a 404 error, but with the .php added to showlisting, it works fine. Any ideas?

However note that the appending of the www. works fine - that's not the part I'm struggling with, although I included that part of the code anyway for full analysis.


Solution

  • Maybe

    RewriteEngine On
    
    RewriteRule ^showlisting/(.*)$ showlisting.php/$1 [L]
    RewriteRule ^listings/(.*)$ listings.php/$1 [L]
    
    RewriteCond %{HTTP_HOST} ^mydomain\.
    RewriteRule ^$ http://www.mydomain.com/ [R=301,L]
    
    ErrorDocument 404 /notfound