Rewriting for RESTful URLs in Apache and Nginx
- 0
- Add a Comment
In my last post, I shared my issues with Apache ignoring the .htaccess file. The reason I was using .htaccess was to create RESTful URLs for my PHP app. I thought that now would be a good time to show how easy it is to do this.
First off, I’ll start by showing you how to rewrite URLs in Apache using mod_rewrite:
1 2 3 4 | RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [L] |
The two RewriteCond statements check to make sure that there is no filename or directory that matches a user’s request. If not, then it rewrites to the index.php page. The [L] means to stop executing rewrites at that line.
Now for Nginx and it’s Rewrite module:
1 2 3 | if (!-e $request_filename) { rewrite ^(.*)$ index.php last; } |
Aside from the more C-style structure, the commands for Nginx and Apache are pretty similar. However Nginx makes it easier by providing the !-e operator, which checks for both files and directories. Remember, there is no .htaccess-equivalent for Nginx, the code above should be placed in the server configuration (most likely in a v-host configuration).
Now, how can I make use of a URL such as example.com/hello/world/ if they get rewritten to index.php? Well, PHP’s $_SERVER superglobal stores valuable information, like the URI typed into the browser to reach the current page. I won’t get into details on that subject, for that is not the focus of this post. Maybe some other time.


