August 17, 2017

Switching from Apache to Nginx: URL Rewriting

With all the awe and wonder of the Internet, one of the most amazing things about its basic function is the speed at which great ideas are shared. Many people use the term “viral” to describe how quickly a great piece of content or information is rapidly spread across the Internet. However, viral content can quickly become quarantined if it is unable to be accessed by the masses. Apache, the current workhorse of the Internet, requires significant hardware resources to effectively handle the sheer volume of traffic synonymous with viral content. A majority of Internet sites can not financially afford the necessary resources to be ready 24/7 for massive traffic. Viral content can die as quickly as it is born, so being able to handle a significant increase in traffic is vital to any website’s potential success. The ideal situation would be to still serve thousands of active visitors on below average hardware: nginx makes that happen.

Pretty urls ( versus have become the norm on the web. These little beauties leverage rewrite engines, and it’s very likely you’re familiar with mod_rewrite if you’ve been using Apache. Rewriting is something you won’t have to sacrifice when making the move to nginx, as it has a full functioning rewrite engine. The transition from mod_rewrite to nginx’s rewrite engine is relatively easy. If you’re familiar with Perl’s implementation of regular expressions, then the switch should be even easier, as nginx url rewriting has some Perl flavor to it.

mod_rewrite basic redirect
RewriteRule [L,R=301]
nginx basic redirect
rewrite permanent;

mod_rewrite WordPress redirect
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
nginx WordPress redirect
if (!-e $request_filename)
   rewrite ^(.+)$ /index.php last;

Like Apache, nginx’s rewrite engine can leverage various system variables to make powerful and precise redirects.

About Michael Marr 12 Articles
Michael Marr is a IT staff Writer for WebProNews.