User Tools

Site Tools


web_servers:nginx

Nginx

See https://www.devdungeon.com/content/nginx-tutorial.

apt install nginx

To add PHP, use PHP FPM

apt install php php-fpm # and others like php-gd
# Control it with something like:
systemctl restart php7.3-fpm
# Config in /etc/php/7.3/fpm

Then in your vhost file, include the following snippet:

  # In your nginx vhost server entry
  index index.php;
  # Have all .php files pass through php-fpm
  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    # Find the right socket in /run/php/
    fastcgi_pass unix:/run/php/php7.3-fpm.sock;
  }

Here is an example nginx site config:

example.nginx.conf
server {
  listen 80;
  listen [::]:80;
  #listen 443 ssl;
  #listen [::]:443 ssl;
 
  server_name www.devdungeon.com;
 
  #ssl_certificate /etc/letsencrypt/live/devdungeon.com/fullchain.pem;
  #ssl_certificate_key /etc/letsencrypt/live/devdungeon.com/privkey.pem;
  #ssl_ciphers  HIGH:!aNULL:!MD5;
 
  # Map a static dir
  location /camserver/static/ {
    alias /path/to/static/;
  }
 
  # Reverse proxy  
  location /camserver/ {
    proxy_pass http://localhost:8002/;
    proxy_set_header X-Real-IP $remote_addr;
  }
 
  # List directory contents
  location /images {
    autoindex on;
    # Use local time instead of UTC for di lists
    autoindex_localtime on;
    alias /path/to/images/;
  }
 
  root /var/www/html/;
  index index.php index.html;
 
  location / {
    try_files $uri $uri/ =404;
  }
 
  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    # Find right socket in /run/php/
    fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    include fastcgi_params;
  }
 
  location ~ /\.ht {
    deny all;
  }
}

If you want to redirect HTTP to HTTPS you can use this redirect snippet. Also you can set the acme directory not to redirect so you can use certbot certonly with webroot config.

redirect.nginx.conf
# Redirect HTTP traffic to HTTPS (both www and non-www)
server {
    listen 0.0.0.0:80;
    listen [::]:80;
 
    server_name mydomain.com www.mydomain.com;
    root /var/www/html/;  # Can probably omit completely
 
    # For Certbot challenges
    location /.well-known/acme-challenge/ {
      alias /var/www/html/.well-known/acme-challenge/;
    }
 
    # Permanent redirect to HTTPS version with www prefix
    return 301 https://www.mydomain.com$request_uri;
}
web_servers/nginx.txt · Last modified: 2022/03/13 18:30 by nanodano