
NGINX je možda najsvestraniji web poslužitelj vani i može nadmašiti druge poslužitelje ako je ispravno konfiguriran. Također može raditi i druge važne stvari, poput uravnoteženja opterećenja, HTTP predmemoriranja, a može se koristiti i kao obrnuti proxy.
Tijekom godina vidjeli smo toliko konfiguracija koje poboljšavaju sigurnost i sveukupno povećavaju performanse vaše web aplikacije - omogućujući vam da idete u korak s najnovijim trendovima.
Dijelit ću minimalističku konfiguraciju NGINX za koju sam ustanovio da je najoptimiziranija koju sam koristio za novi svoj novi alat VisaList. Morao sam puno pretraživati i istraživati kako bih poboljšao performanse svoje web stranice u posljednjoj milji i mislio sam da bi postupak mogao pomoći barem nekolicini drugih - pa ga ovdje dijelim.
Zašto?
Ovim izmjenama uspio sam dobiti rezultat u nastavku za svoju novu web-aplikaciju:
Ocjena brzine stranice : Uvid u brzinu stranice

Ocjena svjetionika: Chrome Dev Tools Svjetionik

Ocjena poslužitelja: Qualys SSL poslužiteljski test

I vi možete lako dobiti ove pogodnosti izvedbe. Vi ne morate biti DevOps stručnjak da bi ove optimizacije. Dakle, svima koji su novi u web aplikacijama i koriste NGINX ovo će biti vrlo korisno.
Ako ste stručnjak, svoje mišljenje možete ostaviti u komentarima kako bi novi razvojni programeri poput mene mogli učiti i izgraditi snažnu i pozitivnu web zajednicu oko nas. ✨ Idite na web programere! ✨
Ovaj članak pretpostavlja da imate poslužitelj Ubuntu 16.04 (Xenial) i poslužitelj koji je pružio aplikaciju WebApp Vue.js (ili bilo koji drugi JS okvir) spreman za posluživanje putem NGINX-a zajedno s API poslužiteljem. Ako niste instalirali NGINX i trebate pomoć u tome, možete pogledati ovaj članak .
Pa o čemu se radi u tim optimizacijama? Da vidimo kod!
Optimizacije
Dobra vijest je da se morate truditi oko dvije datoteke. Jedna je vaša ukupna NGINX konfiguracija, koja se odnosi na sve web aplikacije (možete imati više web aplikacija kao što su web stranica, API, statički poslužitelj itd.). Drugi je specifičan za vašu domenu, što, recimo, jest example.com
. Zamijenite example.com
vlastitom domenom. Ovdje koristim samo golu domenu bez www
. Uskoro ću to pokriti.
Otvorite svoju NGINX konfiguraciju ili konfiguracijske datoteke specifične za domenu pomoću ovih naredbi:
sudo nano /etc/nginx/nginx.conf sudo nano /etc/nginx/sites-available/example.com
Sažimanje sadržaja
Je Brotli bolji od GZip ? Da i Ne. Kada preglednik zatraži web stranicu, poslužitelj je ne šalje izravno po bajt. Umjesto toga, šalje ga u komprimiranom stanju na temelju prihvaćenih kodiranja preglednika. Danas uglavnom svi koriste Gzip, a možda se pitate zašto? Jer postoji već više od deset godina.
Dakle, dolazi Brotli, koji je najnoviji algoritam kodiranja koji je razvio Google. Brotli je ~ 20% učinkovitiji od Gzipa. Samo imajte na umu da biste sadržaj trebali slati u Gzipu tamo gdje Brotli nije podržan. Brotli najbolje radi sa statičkim datotekama, a ne s dinamičkim sadržajem.
Obavezno omogućite i vrstu Brotli za API JSON podatke samo kad to podržava vaša HTTP knjižnica na klijentskoj strani. Na primjer, knjižnica Axios još ne podržava Brotlijevo kodiranje.
http { ... # Gzip Settings gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 32 16k; gzip_http_version 1.1; gzip_min_length 250; gzip_types image/jpeg image/bmp image/svg+xml text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/x-icon; # Brotli Settings brotli on; brotli_comp_level 4; brotli_buffers 32 8k; brotli_min_length 100; brotli_static on; brotli_types image/jpeg image/bmp image/svg+xml text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/x-icon; ... }
Kada dodate ove promjene, možete provjeriti prikazuje li se kodiranje sadržaja br
u zaglavljima odgovora u Chromeovim alatima za programere:

Poboljšajte sigurnost
Prema zadanim postavkama, vaš NGINX nema sva važna sigurnosna zaglavlja, što je zapravo prilično jednostavno. Oni sprječavaju napadaje klikanja, napade skriptiranja na više web lokacija i druge napade ubrizgavanja koda.
Strict-Transport-Security
Zaglavlje je za HTTP Strict Transport Security (HSTS) koja također štiti od napada na smanjenje verzije protokola.
http { ... # security headers add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; ... }
Optimizirajte SSL i sesije
SSL: Koristite na TLS-u i onemogućite SSL (SSL je prilično star i zastario te ima puno ranjivosti). Optimizirajte pakete šifri, jer su oni jezgra TLS-a. Ovdje se događa šifriranje.
Sesijska predmemorija: Stvaranje predmemorije parametara TLS veze smanjuje broj rukovanja i na taj način može poboljšati izvedbu vaše aplikacije. Keširanje se konfigurira pomoću ssl_session_cache
direktive.
Ulaznice za sesije: Ulaznice za sesije su alternativa predmemoriji sesija. U slučaju predmemorije sesije, podaci o sesiji pohranjuju se na poslužitelju.
OSCP: Da bi imao sigurnu vezu s poslužiteljem, klijent mora potvrditi certifikat koji je poslužitelj predstavio. Kako bi potvrdio da certifikat nije opozvan, klijent (preglednik) kontaktirat će izdavatelja certifikata. To dodaje malo više troškova inicijalizaciji veze (a time i vremena učitavanja stranice).
Koristite ove direktive u svojoj NGINX konfiguraciji i svi ste spremni za SSL optimizaciju.
http { ... # SSL Settings ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GC$ # Optimize session cache ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; # Enable session tickets ssl_session_tickets on; # OCSP Stapling ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 208.67.222.222 208.67.220.220 valid=60s; resolver_timeout 2s; ... }
Poboljšajte izvedbu: HTTP / 2 podrška
HTTP / 2 ima puno prednosti u odnosu na HTTP, poput dopuštanja pregledniku da paralelno preuzima datoteke i dopuštanja poslužitelju da gura resurse, između ostalog. Sve što morate učiniti je zamijeniti http
sa http2
u vašem zadanom bloku poslužitelja. To je to i dobit ćete puno, puno prednosti.
server{ ... listen 443 http2 default_server; listen [::]:443 http2 default_server; server_name example.com; ... }
Upišite ovu naredbu curl -I -L //example.com
i provjerite odgovor.
HTTP/2 200 server: nginx date: Wed, 18 Jul 2018 02:13:32 GMT content-type: text/html; charset=utf-8 content-length: 216641 vary: Accept-Encoding ....
Smanjite uklanjanje otpada / napada
Limiting the requests to the server is critical, as this can easily deplete the resources and can result in huge billings. This is also important to fend off those who want to scrape and attack our servers. There are basically three types of directives:
- Request Limiting
limit_req
: Limit the number of requests per IP - Connections Limiting
limit_conn
: Limit the number of Connections per IP - Bandwidth/Rate Limiting
limit_rate
: Limit the bandwidth rate of data being sent
With the below directive, you can rest easy:
http { ... # Limits limit_req_log_level warn; limit_req_zone $binary_remote_addr zone=reqlimit:10m rate=10r/m; limit_conn_zone $binary_remote_addr zone=connlimit:100m; limit_conn servers 1000; # Simultaneous Connections ... }
... server { ... location /api/ { # Rate Limiting limit_req zone=reqlimit burst=20; # Max burst of request limit_req_status 460; # Status to send # Connections Limiting limit_conn connlimit 20; # Number of downloads per IP # Bandwidth Limiting limit_rate 4096k; # Speed limit (here is on kb/s) } ... }
Client-side Caching
Caching static files on the browser is easy, and it saves lot of requests to the server. All you have to do is add these two code blocks and specify the expiration as you please. You can include any other static file extension you deem worthy of caching.
server { ... location / { ... ... } ... ... location ~* \.(jpg|jpeg|png|gif|ico)$ { expires 30d; } location ~* \.(css|js)$ { expires 7d; } ... }
Microcaching
If you haven’t heard about this until now, then you are in luck today! Microcaching is a caching technique in which content is cached for a very short period of time, perhaps as little as 1 second. This effectively means that updates to the site are delayed by no more than a second, which in many cases is perfectly acceptable. This is particularly useful for API responses which are the same for all users.
Use these directives to set microcaching with the path at /tmp/cacheapi
with 100MB cache with a max size of 1GB of cache folder that updates cache in the background. Learn more about it here and here.
proxy_cache_path /tmp/cacheapi levels=1:2 keys_zone=microcacheapi:100m max_size=1g inactive=1d use_temp_path=off; ... server { ... location /api/ { # Micro caching proxy_cache microcacheapi; proxy_cache_valid 200 1s; proxy_cache_use_stale updating; proxy_cache_background_update on; proxy_cache_lock on; ... ... } ... }
http { ... add_header X-Cache-Status $upstream_cache_status; ... }
SSL Certificate
Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates. This enables encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps.
Install LetsEnctypt:
sudo add-apt-repository ppa:certbot/certbot sudo apt-get update sudo apt-get install python-certbot-nginx
Create a LetsEncrypt SSL certificate with this command:
sudo certbot --nginx -d example.com -d www.example.com
and then add these certificates to your domain config file like this:
server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; ... ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ... }
Redirect WWW
Google prefers that you choose a domain with www
instead of without. It’s better to choose the naked domain as its smaller and removes the redundant www
. You can now redirect all www
users to your naked domain by adding these below directives.
server { ... ... } server { listen 80; listen [::]:80; server_name example.com; return 301 //$server_name$request_uri; } server { listen 80; listen [::]:80; listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.example.com; return 301 //example.com$request_uri; }
Pagespeed Module
Pagespeed Module is a gem unknown to many. It was originally a Google Project which is now part of Apache Incubator. Pagespeed can automatically take care of almost all the known ways to improve performance on your website.
Installor Upgrade NGINX with Pagespeed. This is not an easy task, and that’s why I have saved it for last. Follow these instructions, and you should be able to do it without any hastle. Once you’re done, all you need to do is enable it and voilà!
server{ ... # Pagespeed Module pagespeed on; pagespeed FileCachePath /var/cache/ngx_pagespeed_cache; location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; } location ~ "^/pagespeed_static/" { } location ~ "^/ngx_pagespeed_beacon$" { } pagespeed RewriteLevel PassThrough; pagespeed EnableCachePurge on; pagespeed PurgeMethod PURGE; pagespeed EnableFilters prioritize_critical_css; ... }
There are so many filters that you can enable, but just keep in mind that most of the modern frameworks like (Nuxt.js, Angular, Next.js and so on) have some of these optimisations as part of their build process, so this can be counterintuitive. Choose filters which you need and enable only them. This is not by any means an exhaustive set of filters, but would definitely take your site to 100/100 on pagespeed.
pagespeed EnableFilters rewrite_css; pagespeed EnableFilters collapse_whitespace,remove_comments; pagespeed EnableFilters flatten_css_imports; pagespeed EnableFilters combine_css; pagespeed EnableFilters combine_javascript; pagespeed EnableFilters defer_javascript; pagespeed EnableFilters extend_cache; pagespeed EnableFilters pedantic; pagespeed EnableFilters inline_google_font_css; pagespeed FetchHttps enable; pagespeed EnableFilters inline_css,move_css_above_scripts; pagespeed EnableFilters inline_javascript; pagespeed EnableFilters inline_import_to_link; pagespeed EnableFilters lazyload_images; pagespeed EnableFilters insert_dns_prefetch; pagespeed EnableFilters inline_preview_images; pagespeed EnableFilters resize_mobile_images; pagespeed EnableFilters rewrite_images; pagespeed EnableFilters responsive_images,resize_images; pagespeed EnableFilters responsive_images_zoom; pagespeed EnableFilters rewrite_javascript; pagespeed EnableFilters rewrite_style_attributes,convert_meta_tags;
You can read more about different types of filters available here.
So the final NGINX config and domain config looks something like this:
//gist.github.com/1hakr/01cb00dfce8c92a15c0d9faee9052042
Now all you have to do is reload your NGINX config file by typing the below commands and you have supercharged your NGINX server:
sudo nginx -t sudo systemctl restart nginx
Pro Tip: If you find this article beyond your reach, then there is a simple website which can get the final config file for you: check out NGINX Config.
I hope you like this NGINX config and are able to supercharge your web apps. Do you already use something similar or have a different opinion altogether? Let me know in the comments.
This is my new microstartup, VisaList, where I have applied these optimisations. It can help you find visa requirements for all countries in the world in a simple and useful way.
Find countries to visit across the world
Search from list of countries your can travel with Visa free, Visa on arrival and other requirements from more than…
visalist.io
That all folks! This is HaKr signing off. Thanks for reading, and if you found this useful do click ? to recommend this article to others so they can find it, too.
I build microstartups while travelling when I can. If you find this kind of stuff interesting, you can follow me on Twitter and check out my open-source work on GitHub.