If you are like me, you already know how to use MOD-REWRITE in apache2, but need guidance to implement things in nginx !
There are three directives in nginx concerning rewriting, namely return, rewrite, and try_files Directives, what i will be starting with is rewrite, since most websites on Apache use “rewrite_rule” which can be easily translated into rewrite
I will also provide the most common examples for software such as WordPress, laravel, and other software so that you can get up and running in the shortest possible time
1- Translating my RewriteRule from Apache into nginx
The good news is, it is very easy, I will provide a few simple guidelines, then provide examples.
- The counterpart to RewriteRule in apache2 in nginx is rewrite, so start by changing the text RewriteRule into rewrite
- Replace [L] or [QSA,L] with the string “last;”, Notice that configuration entries in nginx end in a semicolon
- Wherever there is an occurrence of ^ follow it with a /, Making it ^/
- In nginx, curly braces are used for two purposes, block control and regular expressions, so if your existing apache2 rules contain those curly braces for regular expressions, you can tell nginx that this is a regular expression not block control by surrounding the regular expression with quotes (double or single).
So let me create an example, explain what it does, and show you how it is translated into nginx rewrite
What it does | In Apache | In nginx |
This rewrites everything onto the index.php file, except for the contents of one folder named norewrite | * RewriteEngine on * RewriteRule ^norewrite(.) – [L] * RewriteRule ^(.)$ index.php?q=$1 [L,QSA] | Create a separate section for the folder norewrite, and then use the following * rewrite ^(.*)$ /index.php?q=$1 last; |