Question

I am trying to rewrite my URLs to have clean URLs. For example I want the following URL rewritten like so:

www.domain.com/events/events.php

www.domain.com/events/

It is rewritting the URL correctly but the rewritten URL is giving a 404 error. What am I doing wrong?

I am using the following rule:

RewriteCond %{THE_REQUEST} ^(GET|POST)\ /(.*)/(.*)\.php\ HTTP
RewriteRule ^ http://www.domain.com/%3/? [R=301,L]
Was it helpful?

Solution

Once you've got the rules to externally redirect the browser, you then need to add rules to internally rewrite to the actual files. So you need to add:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /$1/$1.php [L]

Now, this rule takes a URI that looks like /(something)/ to /(something)/(something).php. So:

  • /foo/ to /foo/foo.php
  • /example/ to /example/example.php

etc.

There's no other info you're providing in the rewritten URI that tells you what the php filename is, so if you have something like this:

  • /foo/bar.php

there's no way to extract the "bar" out of /foo/. You'd need to additionally encode that in the clean url:

RewriteCond %{THE_REQUEST} ^(GET|POST)\ /(.*)/(.*)\.php\ HTTP
RewriteRule ^ http://www.domain.com/%2/%3/? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ /$1/$2.php [L]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top