So I’ve been searching for a while now and can’t find anything specific on how to create a pretty url / seo / slug url type system WITHOUT sending everything to a index.php or moving things into subfolders.
Basically I’m making a website which you can currently go to urls like movie.php?id=#### / show.php?id=####. Ideally I’d like the url to be movie/#### or movie/id/#### (or down the line slugs of the name that i can use to grab the right one) etc.
Is there a way to do it without having a single index.php router or am I just going to have to rewrite all my files to adhere to this style?
2
Answers
Yes, assuming your URL structure follows a relatively consistent pattern, you can definitely do this with an .htaccess file and mod_rewrite (without the need for an index.php file, commonly referred to as a front controller).
Here’s a really simple example:
This takes an incoming URL like http://example.com/movie/3 and performs a transparent/internal rewrite (so the user doesn’t see the URL change) to http://example.com/movie.php?id=3.
Of course, this example could be expanded to handle more parameters, etc. but hopefully this gets you started on the right path. I highly recommend you read the mod_rewrite documentation for more details: http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
You can create a rewrite rule in .htaccess that routes the movie urls to movie.php as follows:
movie/123:
movie/id/123:
movie/title-of-movie:
movie/title/title-of-movie:
combination movie/123/title-of-movie:
Edit: added a full .htaccess example for 1 required with up to 2 extra optional parameters with a fallback on index.php if the url is not for movies.
^
to match from the beginning$
to match until the end?
for 0 or 1 occurrence+
for 1 or more occurrences*
for 0 or more occurrencesIf the url rule does not match and the file does not exist then it will route the url to index.php, but you can remove that last part if you don’t want that.