How to do URL routing (MOD_REWRITE) for both IIS and Apache
Usually I work on Windows OS with IIS and then I publish the smaller apps on shared hosting. This is why I hate making complicated configuration adding a lot of regular expression strings to route.
The mod_rewrite Apache module is one of a webmaster’s most valuable tools. It allowing you to manipulate URLs in countless ways. A mod_rewrite can be complex because of the many functions it offers. But if you know precisely what kind of URL manipulation you need, it can be done easy.
The simple instructions for designing mod_rewrite under shared hosting using cPanel:
- Log on to cPanel.
- Click on “File Manager.”
- Navigate to your root directory (public_html).
- Click the “.htaccess” file, then click “Edit.”
- Type “RewriteEngine On” to enable mod_rewrite. You can use mod_rewrite to write a number of commands such as controlling access to your website and redirecting visitors. To redirect your domain to another directory type the following:
RewriteEngine On RewriteRule ^/?restapi/v1/([a-z/.]+)$ restapi/api.php?route=$1 [R=301,L]
- Click “Save Changes.”
Note that you shall do this rewrite rule under root of your hosting. In case you have multiple applications installed there you shall correct the regular expressions according to your paths.
Under Windows OS you first need to install URL Rewrite module into IIS.
Install the Microsoft Web Platform Installer (Web PI). This is a free tool that helps administrators get the latest components of the Microsoft Web Platform, including IIS, SQL Server Express, .NET Framework and Visual Web Developer. Once installed, do a search for routing, select Application Request Routing 2.5 with KB2589179 or Application Request Routing 3, click Add and then click Install to start the installation of ARR.
Once installed you will have new icons in IIS – URL Rewrite
Go to the virtual folder, site or application you want to address and open URL Rewrite. Add new blank rule.
Under “Match URL” set your regular expression
^v1/(.+)$
and under “Action” set your replace string
api.php?route={R:1}
You can keep the “Append query string” checked.
You can test the Match URL expression with some test URL until you’r see the expected result.
After all this you just need one api.php file where you can parse the “route” query param and redirect to or include a different PHP-file.