Nginx

18 Notes
+ Enables gzip compression (March 30, 2020, 12:14 p.m.)

# most people include something like this. don't. # check your default nginx.conf, it's already covered in a much better way. #gzip_disable "MSIE [1-6]\.(?!.*SV1)"; # compress proxied requests too. # it doesn't actually matter if the request is proxied, we still want it compressed. gzip_proxied any; # a pretty comprehensive list of content mime types that we want to compress # there's a lot of repetition here because different applications might use different # (and possibly non-standard) types. we don't really care, we still want them included # don't include text/html -- it is always included anyway gzip_types text/css text/plain text/javascript application/javascript application/json application/x-javascript application/xml application/xml+rss application/xhtml+xml application/x-font-ttf application/x-font-opentype application/vnd.ms-fontobject image/svg+xml image/x-icon application/rss+xml application/atom_xml; # increase the compression level, at the expense of additional CPU # cpu cycles are cheap virtually everywhere now, bandwidth not nearly as much gzip_comp_level 9; # the default is to gzip only HTTP 1.1 requests # we want to gzip http 1.0 requests, too, so lower the level required gzip_http_version 1.0; # set the Vary: Accept-Encoding header to force proxies to store compressed and uncompressed versions # per the nginx docs, a bug in IE 4 - 6 will cause them to not cache anything with this on # most people aren't going to care about ie 6 anymore, but keep that in mind gzip_vary on; # increase the size of the buffers which hold responses to make sure larger content can be compressed too # this means there are 16 buffers and they can each hold 8k # if you serve a lot of ridiculously large text (like combined CSS) you might consider upping this slightly gzip_buffers 16 8k; # up the minimum length a little to account for gzip overhead # this means anything smaller than 50 bytes won't be compressed. # the default is 20 bytes, which is sooo tiny it's a waste to compress gzip_min_length 50;

+ Serving Angular application (Oct. 8, 2019, 1:10 a.m.)

server { listen 80; server_name tiptong.ir www.tiptong.ir; index index.html; root /srv/tiptong; location / { try_files $uri$args $uri$args/ /index.html; } }

+ Change 502 Bad Gateway Error page (Oct. 1, 2019, noon)

1- Create an empty HTML file: sudo touch /srv/blank.html 2- Edit the nginx config file: location / { uwsgi_pass 127.0.0.1:22220; include uwsgi_params; error_page 502 = /blank.html; } location = /blank.html { root /srv/; }

+ Remove favicon.ico error_log (June 25, 2019, 10:34 a.m.)

location = /favicon.ico { access_log off; log_not_found off; }

+ Serving robots.txt (Aug. 22, 2014, 8:04 a.m.)

location /robots.txt { alias /path/to/static/robots.txt; }

+ Fix Django Invalid HTTP_HOST header emails (June 3, 2018, 6:55 p.m.)

Add this block in "http" block of /etc/nginx/nginx.conf file. server { listen 80; server_name _; return 444; } Keep in mind to place the block before the include config files.

+ Forward port 80 to 8080 (Dec. 15, 2018, 1:53 p.m.)

server { listen 80; server_name stats.mohsenhassani.com; location / { proxy_pass http://127.0.0.1:8080; } }

+ Set Up HTTP Authentication on a Directory (April 11, 2017, 12:58 p.m.)

1- apt install apache2-utils nginx-extras 2- htpasswd -c /etc/nginx/.htpasswd mohsen Note that this htpasswd should be accessible by the user-account that is running Nginx. 3- server { listen 80; server_name ftp.mohsenhassani.com; location / { fancyindex on; fancyindex_exact_size off; root /home/mohsen/ftp; } location /private { auth_basic "This is private zone!"; auth_basic_user_file /etc/nginx/.htpasswd; fancyindex on; fancyindex_exact_size off; alias /home/mohsen/ftp/private; } }

+ Create an SSL Certificate (Sept. 16, 2016, 3:16 a.m.)

1- Creating a directory that will be used to hold all of our SSL information. It should be created under the Nginx configuration directory: sudo mkdir /etc/nginx/ssl ------------------------------------------------------------------ 2- Create the SSL key and certificate files: (There is a sample some blocks below for the questions asked): openssl req -x509 -nodes -days 365 -newkey rsa:2048 -sha256 -keyout /etc/nginx/ssl/mohsenhassani_private.key -out /etc/nginx/ssl/mohsenhassani_public.pem OR (insert the informations all together in here): sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -sha256 -keyout /etc/nginx/ssl/mohsenhassani_private.key -out /etc/nginx/ssl/mohsenhassani_public.pem -subj "/C=IR/ST=Tehran/L=Tehran/O=NozhanModern/CN=bot.mohsenhassani.com" ------------------------------------------------------------------ 3-We will be asked a few questions about our server in order to embed the information correctly in the certificate. The most important line is the one that requests the Common Name (e.g. server FQDN or YOUR name). You need to enter the domain name that you want to be associated with your server. You can enter the public IP address instead if you do not have a domain name. ------------------------------------------------------------------ 4-Configure Nginx to Use SSL: server { listen 80; listen 443 ssl; server_name bot.mohsenhassani.com; ssl_certificate /etc/nginx/ssl/mohsenhassani_public.pem; ssl_certificate_key /etc/nginx/ssl/mohsenhassani_private.key; } ------------------------------------------------------------------------------- A sample of questions asked: Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:New York Locality Name (eg, city) []:New York City Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc. Organizational Unit Name (eg, section) []:Ministry of Water Slides Common Name (e.g. server FQDN or YOUR name) []:server_IP_address Email Address []:admin@your_domain.com ------------------------------------------------------------------------------- Descriptions: You will be asked a series of questions. Before we go over that, let's take a look at what is happening in the command we are issuing: openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files. req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The "X.509" is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. We want to create a new X.509 cert, so we are using this subcommand. -x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed certificate instead of generating a certificate signing request, as would normally happen. -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Nginx to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening because we would have to enter it after every restart. -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here. -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long. -keyout: This line tells OpenSSL where to place the generated private key file that we are creating. -out: This tells OpenSSL where to place the certificate that we are creating.

+ Permanently Redirect URLs (May 21, 2016, 3:03 p.m.)

server { listen 80; server_name mohsenhassani.ir www.mohsenhassani.ir 89.23.11.120; return 301 https://www.mohsenhassani.ir$request_uri; } server { listen 443 ssl http2; server_name mohsenhassani.ir www.mohsenhassani.ir 89.23.11.120; # The rest of the configuration ... } ------------------------------------------------------------------------ Redirect All Request to Specific URL: This will redirect all incoming requests on the domain to URL http://anotherdomain.com/dir1/index.php, as configured below. server { listen 192.168.1.100:80; server_name mydomain.com; return 301 http://anotherdomain.com/dir1/index.php; } ------------------------------------------------------------------------ Redirect All Request to Other Domain: This will redirect all incoming requests on the domain to another domain (http://anotherdomain.com/) with corresponding request URL and query strings. server { listen 192.168.1.100:80; server_name mydomain.com; return 301 http://anotherdomain.com$request_uri; } ------------------------------------------------------------------------ Redirect Requests with Protocol Specific: This will redirect all incoming requests on the domain to another domain (http://anotherdomain.com/) with corresponding request URL and query strings. Also, it will use the same protocol on redirected URL. server { listen 192.168.1.100:80; server_name mydomain.com; return 301 $scheme://anotherdomain.com$request_uri; } ------------------------------------------------------------------------

+ Serve HTML file (May 17, 2016, 4:04 a.m.)

server { root /srv/websites/my_website; listen 80; server_name mohsenhassani.com www.mohsenhassani.com; index index.html index.htm; # proxy request to node location @proxy { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:3010; proxy_redirect off; break; } location / { try_files $uri $uri/ @proxy; } }

+ PHP Configuration (March 13, 2016, 9:22 p.m.)

server { listen 80; server_name 10.10.0.237; root /var/www/suitecrm; index index.php index.html index.htm index.nginx-debian.html; access_log /var/log/nginx/suitecrm.access.log; error_log /var/log/nginx/suitecrm.error.log; client_max_body_size 300M; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.3-fpm.sock; } } ------------------------------------------------------- In case of errors, try checking (tail -f) the access.log and error.log files. If no output in errors.log, check if the socket file "php7.3-fpm.sock" exists in the path mentioned in "location ~ \.php$" directive. -------------------------------------------------------

+ Https with Django (March 13, 2016, 9:30 p.m.)

mkdir /etc/nginx/ssl openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt openssl req -newkey rsa:2048 -sha256 -nodes -keyout /home/mohsen/ssl/PRIVATE.key -x509 -days 365 -out /home/mohsen/ssl/PUBLIC.pem -subj "/C=IT/ST=state/L=location/O=description/CN=telegram.mohsenhassani.com" --------------------------THIS IS THE OUTPUT -------------------------- [sudo] password for mohsen: Generating a 2048 bit RSA private key ..+++ ...................+++ writing new private key to '/etc/nginx/ssl/nginx.key' /etc/nginx/ssl/nginx.key: No such file or directory 3073349308:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('/etc/nginx/ssl/nginx.key','w') 3073349308:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400: mohsen@mohsenhassani:~$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt Generating a 2048 bit RSA private key .......+++ ............................................................................................................+++ writing new private key to '/etc/nginx/ssl/nginx.key' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:New York Locality Name (eg, city) []:New York City Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc. Organizational Unit Name (eg, section) []:Ministry of Water Slides Common Name (e.g. server FQDN or YOUR name) []:notes.mohsenhassani.com --------------------------THIS IS THE OUTPUT -------------------------- The nginx sample config file: server { listen 80; listen 443 ssl; server_name notes.mohsenhassani.com notes.mohsenhassani.ir; access_log /home/mohsen/logs/notes_mohsen.access.log; error_log /home/mohsen/logs/notes_mohsen.error.log; ssl_certificate /etc/nginx/ssl/nginx.crt; ssl_certificate_key /etc/nginx/ssl/nginx.key; add_header Access-Control-Allow-Origin '*'; location / { uwsgi_pass 127.0.0.1:22222; include uwsgi_params; uwsgi_read_timeout 6000s; uwsgi_send_timeout 6000s; } client_max_body_size 20M; location /static/admin/ { gzip on; alias /home/mohsen/virtualenvs/django-1.8/lib/python3.4/site-packages/django/contrib/admin/static/admin/; } location /media/ { gzip on; alias /home/mohsen/websites/notes_mohsen/notes/media/; } location /static { gzip on; alias /home/mohsen/websites/notes_mohsen/notes/static; } }

+ Access-Control-Allow-Origin downloading a JSON file (Dec. 23, 2015, 12:36 p.m.)

Add this line to server { } block: add_header Access-Control-Allow-Origin '*'; Example: server { listen 80; server_name notes.mohsenhassani.com notes.mohsenhassani.ir; access_log /home/mohsen/logs/notes.access.log; error_log /home/mohsen/logs/notes.error.log; add_header Access-Control-Allow-Origin '*'; location / { uwsgi_pass 127.0.0.1:22222; include uwsgi_params; uwsgi_read_timeout 6000s; uwsgi_send_timeout 6000s; } client_max_body_size 20M; location /static/admin/ { gzip on; alias /home/mohsen/virtualenvs/django-1.8/lib/python3.4/site-packages/django/contrib/admin/static/admin/; } location /media/ { gzip on; alias /home/mohsen/websites/notes/notes/media/; } location /static { gzip on; alias /home/mohsen/websites/notes/notes/static; } }

+ Nginx Serve Fonts (Oct. 14, 2015, 3:18 p.m.)

add_header Access-Control-Allow-Origin '*'; location / { uwsgi_pass 127.0.0.1:22222; include uwsgi_params; uwsgi_read_timeout 6000s; uwsgi_send_timeout 6000s; location ~* \.(ttf|ttc|otf|eot|woff|font.css)$ { add_header "Access-Control-Allow-Origin" "*"; } }

+ Nginx and uWSGI confirguration (Aug. 22, 2014, 8:04 a.m.)

1-Install nginx using its help 2-Install uwsgi ==> pip install uwsgi; It needs ==> easy_install pip, and apt-get install python-dev 3-Copy the myuwsgi in /etc/init.d 4-Make sure you have the command /usr/local/bin/uwsgi or /usr/bin/uwsgi 5-Copy the config file of the website in web_cofings

+ Configurations (Feb. 4, 2016, 9:49 a.m.)

nano /etc/nginx/nginx.conf Add the following line: include /home/mohsen/web_configs/*; Afte these lines: include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; -------------------------------------------------------------- To start nginx /usr/local/nginx/sbin/nginx -------------------------------------------------------------- For establishing a local Django project, I have to first know what the connected Modem IP address is, so that I can give this IP address to nginx "server_name". I thought it's "localhost" or "127.0.0.1", but it was not! It's local IP address! I thought it would be 192.168.1.2, but it's still not! It's the IP address of Modem. How to get the IP I need? It's done using "ifconfig". Using this command, I could see the IP that the Modem has given to the Computer. So it should be used in "server_name" of nginx.

+ Installation (Feb. 4, 2016, 9:46 a.m.)

apt install nginx libpcre3-dev