Search code examples
phphttpurlurl-mapping

Clean URLs with PHP


So I am trying to build a clean url system in PHP to change URLS like this http://example.com/index.php?projects=05 to: http://example.com/projects/05

So far, I have figured out how to use parse_url to map urls that look like http://example.com/index.php/projects/05 but I can't figure out how to remove the 'index.php' from the URL. Is there a way to use .htaccess to remove index.php from the url string?

I know this is sort of a simple problem but after extensive googling, I can't find a solution.


Solution

  • You'll need to do this in Apache using mod_rewrite. You'll need to redirect all URLs to to your index.php and then, maybe using parse_url, figure out what to do with them.

    For example:

    # Turn on the rewrite engine
    RewriteEngine On
    
    # Only redirect if the request is not for index.php
    RewriteCond %{REQUEST_URI} !^/index\.php
    
    # and the request is not for an actual file
    RewriteCond %{REQUEST_FILENAME} !-f
    
    # or an actual folder
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # finally, rewrite (not redirect) to index.php
    RewriteRule .* index.php [L]