This question already has answers here:
Closed 10 months ago.
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.
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]
I am using the following .htaccess file to remove the index.php part of the url.
# Turn on URL rewriting
RewriteEngine On
# Installation directory
RewriteBase /
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !favicon.ico$
RewriteRule .* index.php/$0 [PT]
Otherwise I can recommend the Kohana framework as a reference (they also have a fairly nice url parser and controller system)
The concept of decoupling the actual files/folders from the URL is called routing. Many PHP frameworks include this kind of functionality, mostly using mod_rewrite. There is a nice blog post on PHP URL Routing that implements a simple standalone router class.
It creates mapping like this:
mysite.com/projects/show/1 --> Projects::show(1)
So the requested URL results in the function show()
of the class Projects
being called, with the parameter of 1
.
You can use this to build flexible mappings of pretty URLs to your PHP code.
Something like this in your .htaccess :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
(Be sure the rewrite module is enabled)