Forum Discussion

Razzera's avatar
Razzera
Icon for Nimbostratus rankNimbostratus
Nov 27, 2022

.htaccess to Nginx rules

My website was working fine with Apache .htaccess rules. Now I have sifted it to nginx because ofa new server. I need help to convert following apache rules to nginx directives/configurations.

also, where in my ./etc/nginx/sites-enabled/thesite.com.conf should i pages the rules ?

What i want to translate to Nginx Directives

RewriteEngine On
RewriteCond %{REQUEST_URI} ^(.+)\~s$
RewriteRule ^(.*) /stats.php?url=$1 [L]
RewriteCond %{REQUEST_URI} ^(.+)\~q$
RewriteRule ^(.*) /generate_qr.php?url=$1 [L]
RewriteCond %{REQUEST_URI} ^(.+)\~p$
RewriteRule ^(.*) /preview_url.php?url=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) /url_redirector.php?url=$1 [L]

Nginx Config

server {
  listen 80;
  listen [::]:80;
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  ssl_certificate_key /etc/nginx/ssl-certificates/site.com.key;
  ssl_certificate /etc/nginx/ssl-certificates/site.com.crt;
  server_name site.com www1.site.com;
  root /home/site/htdocs/site.com;

  access_log /home/site/logs/nginx/access.log main;
  error_log /home/site/logs/nginx/error.log;

  if ($scheme != "https") {
    rewrite ^ https://$host$uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header X-Varnish;
    proxy_redirect off;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      720;
    proxy_send_timeout         720;
    proxy_read_timeout         720;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
    add_header Access-Control-Allow-Origin "*";
    expires max;
    access_log off;
  }

  if (-f $request_filename) {
    break;
  }
}