I've been trying for two days to convert an .htaccess to nginx rewrite the original file looked like this:
# Turn on URL rewriting
RewriteEngine On
RewriteBase //
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]
# List of files in subdirectories will not be displayed in the browser
Options -Indexes
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
AddDefaultCharset utf-8
AddCharset UTF-8 .htm .html .txt
AddType "text/html; charset=UTF-8" .htm .html .txt
AddType "text/css; charset=UTF-8" .css
AddType "text/javascript; charset=UTF-8" .js
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
I have managed to come up with this:
# nginx configuration
charset utf-8;
autoindex off;
location /application {
rewrite ^/(?:application|modules|system)\b.* /index.php/$0 break;
}
location /modules {
rewrite ^/(?:application|modules|system)\b.* /index.php/$0 break;
}
location /system {
rewrite ^/(?:application|modules|system)\b.* /index.php/$0 break;
}
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php/$0;
}
}
location ~ \.* {
deny all;
}
But when I restart nginx I get:
[emerg] unknown "0" variable
nginx: configuration file /etc/nginx/nginx.conf test failed
I do not understand why this is. Can someone pleas help me with this?
Best Answer
nginx does not have the
$0
variable, which is used in Apache for the whole regex pattern match in Apache.In nginx, you get the equivalent string by using
$request_uri
.So, you should use a configuration like this:
I also fixed the hidden files regex here.