Convert Figma logo to code with AI

lebinh logonginx-conf

A collection of useful Nginx configuration snippets

2,126
352
2,126
2

Top Related Projects

26,708

The official NGINX Open Source repository.

Nginx HTTP server boilerplate configs

⚙️ NGINX config generator on steroids 💉

A collection of resources covering Nginx, Nginx + Lua, OpenResty and Tengine

How to improve NGINX performance, security, and other important things.

NGINX tuning for best performance

Quick Overview

The lebinh/nginx-conf repository is a collection of NGINX configuration files and examples. It provides a comprehensive set of pre-configured NGINX setups for various use cases, serving as a reference and starting point for NGINX administrators and developers.

Pros

  • Extensive collection of NGINX configuration examples
  • Well-organized and categorized configurations
  • Includes configurations for common scenarios and advanced use cases
  • Regularly updated with new examples and best practices

Cons

  • May require adaptation for specific production environments
  • Some configurations might be outdated or not follow the latest NGINX best practices
  • Limited documentation on individual configuration files
  • Lacks detailed explanations for complex setups

Getting Started

To use these NGINX configurations:

  1. Clone the repository:

    git clone https://github.com/lebinh/nginx-conf.git
    
  2. Navigate to the desired configuration file or example.

  3. Copy the relevant parts of the configuration to your NGINX setup.

  4. Modify the configuration as needed for your specific use case.

  5. Test the configuration:

    nginx -t
    
  6. Reload NGINX to apply changes:

    nginx -s reload
    

Remember to review and understand each configuration before applying it to your production environment.

Competitor Comparisons

26,708

The official NGINX Open Source repository.

Pros of nginx

  • Official repository maintained by NGINX, Inc.
  • Comprehensive codebase with full NGINX functionality
  • Extensive documentation and community support

Cons of nginx

  • Large codebase can be overwhelming for beginners
  • Requires compilation for custom modules or features
  • More complex setup for simple configuration needs

Code Comparison

nginx:

ngx_int_t
ngx_http_core_content_phase(ngx_http_request_t *r,
    ngx_http_phase_handler_t *ph)
{
    size_t     root;
    ngx_int_t  rc;
    ngx_str_t  path;

nginx-conf:

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;
    index index.html;
}

The nginx repository contains the full source code of the NGINX web server, including core functionality and modules. It's written primarily in C and requires compilation to implement changes or add custom features.

In contrast, the nginx-conf repository focuses on configuration examples and best practices for NGINX. It provides ready-to-use configuration files in the NGINX configuration language, making it easier for users to set up and customize their NGINX installations without diving into the source code.

While nginx offers complete control and customization, nginx-conf is more accessible for users who primarily need to configure NGINX for their specific use cases without modifying the underlying server code.

Nginx HTTP server boilerplate configs

Pros of server-configs-nginx

  • More comprehensive and well-documented configuration examples
  • Regularly updated with contributions from a larger community
  • Includes performance optimizations and security best practices

Cons of server-configs-nginx

  • Can be overwhelming for beginners due to its extensive options
  • May require more customization to fit specific use cases

Code Comparison

server-configs-nginx:

# Compression
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;

nginx-conf:

# Compression
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;

Summary

server-configs-nginx offers a more comprehensive and well-maintained set of NGINX configurations, with a focus on performance and security. It benefits from a larger community and regular updates. However, its extensive options may be overwhelming for beginners.

nginx-conf provides a simpler approach, which can be easier for newcomers to understand and implement. It may require less customization for basic setups but might lack some of the advanced features and optimizations found in server-configs-nginx.

Both repositories offer similar core functionalities, as seen in the compression configuration example. The choice between them depends on the user's experience level and specific project requirements.

⚙️ NGINX config generator on steroids 💉

Pros of nginxconfig.io

  • Interactive web-based interface for generating NGINX configurations
  • Provides a user-friendly approach for less experienced users
  • Offers a wide range of pre-configured options and best practices

Cons of nginxconfig.io

  • Less flexible for advanced or custom configurations
  • Requires an internet connection to use the tool
  • May not cover all possible NGINX configuration scenarios

Code Comparison

nginx-conf:

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;
    index index.html;
}

nginxconfig.io (generated output):

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    root /var/www/example.com;
    index index.html;
    
    # Additional security headers and optimizations
    include security.conf;
    include general.conf;
}

Summary

nginx-conf is a collection of NGINX configuration examples, while nginxconfig.io is an interactive tool for generating NGINX configurations. nginx-conf provides more flexibility for advanced users but requires manual editing. nginxconfig.io offers a user-friendly interface with pre-configured options, making it easier for beginners but potentially limiting for complex setups. The code comparison shows that nginxconfig.io generates more comprehensive configurations with additional security and optimization features by default.

A collection of resources covering Nginx, Nginx + Lua, OpenResty and Tengine

Pros of nginx-resources

  • Comprehensive collection of NGINX resources, including articles, books, and tools
  • Regularly updated with new content and contributions from the community
  • Covers a wide range of NGINX-related topics, from basic configuration to advanced use cases

Cons of nginx-resources

  • Lacks actual configuration examples, focusing more on external resources
  • May require more time to find specific information due to the breadth of content
  • Does not provide ready-to-use configuration templates

Code comparison

nginx-conf:

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;
    index index.html;
}

nginx-resources:

## Books

- [NGINX Cookbook](https://www.nginx.com/resources/library/complete-nginx-cookbook/)
- [NGINX HTTP Server](https://www.packtpub.com/product/nginx-http-server-fourth-edition/9781788623124)

nginx-conf provides actual NGINX configuration examples, while nginx-resources offers a curated list of external resources for learning and reference.

How to improve NGINX performance, security, and other important things.

Pros of nginx-admins-handbook

  • More comprehensive and detailed documentation
  • Covers advanced topics and best practices
  • Includes security considerations and performance optimization tips

Cons of nginx-admins-handbook

  • May be overwhelming for beginners
  • Less focused on specific configuration examples
  • Requires more time to navigate and find relevant information

Code Comparison

nginx-admins-handbook:

server {
    listen 443 ssl http2;
    server_name example.com;
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    # Additional SSL configuration...
}

nginx-conf:

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;
    index index.html;
}

nginx-admins-handbook provides a more advanced example with SSL and HTTP/2 configuration, while nginx-conf offers a simpler, basic server block setup.

nginx-admins-handbook is a comprehensive guide for NGINX administrators, covering various aspects of configuration, security, and optimization. It's ideal for those seeking in-depth knowledge and best practices.

nginx-conf, on the other hand, is a collection of example configurations, making it more suitable for quick reference and practical implementation. It's particularly useful for those who prefer learning through concrete examples.

NGINX tuning for best performance

Pros of nginx-tuning

  • More comprehensive tuning options, covering a wider range of NGINX configurations
  • Includes detailed explanations and comments for each configuration option
  • Regularly updated with the latest NGINX best practices and security recommendations

Cons of nginx-tuning

  • Less organized structure compared to nginx-conf
  • May be overwhelming for beginners due to the extensive number of options
  • Lacks specific use-case examples or templates

Code Comparison

nginx-tuning:

worker_processes auto;
worker_rlimit_nofile 100000;
events {
    worker_connections 4000;
    use epoll;
    multi_accept on;
}

nginx-conf:

worker_processes auto;
events {
    worker_connections 1024;
}
http {
    include mime.types;
    default_type application/octet-stream;
}

The nginx-tuning example provides more advanced configuration options, while nginx-conf offers a simpler, more basic setup. nginx-tuning includes additional performance-related settings like worker_rlimit_nofile, use epoll, and multi_accept, which are not present in the nginx-conf example.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Nginx Configuration Snippets

A collection of useful Nginx configuration snippets inspired by .htaccess snippets.

Table of Contents

The Nginx Command

The nginx command can be used to perform some useful actions when Nginx is running.

  • Get current Nginx version and its configured compiling parameters: nginx -V
  • Test the current Nginx configuration file and / or check its location: nginx -t
  • Reload the configuration without restarting Nginx: nginx -s reload

Rewrite and Redirection

Force www

The right way is to define a separated server for the naked domain and redirect it.

server {
    listen 80;
    server_name example.org;
    return 301 $scheme://www.example.org$request_uri;
}

server {
    listen 80;
    server_name www.example.org;
    ...
}

Note that this also works with HTTPS site.

Force no-www

Again, the right way is to define a separated server for the www domain and redirect it.

server {
    listen 80;
    server_name example.org;
}

server {
    listen 80;
    server_name www.example.org;
    return 301 $scheme://example.org$request_uri;
}

Force HTTPS

This is also handled by the 2 server blocks approach.

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;

    # let the browsers know that we only accept HTTPS
    add_header Strict-Transport-Security max-age=2592000;

    ...
}

Force Trailing Slash

This configuration only add trailing slash to URL that does not contain a dot because you probably don't want to add that trailing slash to your static files. Source.

rewrite ^([^.]*[^/])$ $1/ permanent;

Redirect a Single Page

server {
    location = /oldpage.html {
        return 301 http://example.org/newpage.html;
    }
}

Redirect an Entire Site

server {
    server_name old-site.com
    return 301 $scheme://new-site.com$request_uri;
}

Redirect an Entire Sub Path

location /old-site {
    rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;
}

Performance

Contents Caching

Allow browsers to cache your static contents for basically forever. Nginx will set both Expires and Cache-Control header for you.

location /static {
    root /data;
    expires max;
}

If you want to ask the browsers to never cache the response (e.g. for tracking requests), use -1.

location = /empty.gif {
    empty_gif;
    expires -1;
}

Gzip Compression

gzip  on;
gzip_buffers 16 8k;
gzip_comp_level 6;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
gzip_types
    text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
    text/javascript application/javascript application/x-javascript
    text/x-json application/json application/x-web-app-manifest+json
    text/css text/plain text/x-component
    font/opentype application/x-font-ttf application/vnd.ms-fontobject
    image/x-icon;
gzip_disable  "msie6";

Open File Cache

If you have a lot of static files to serve through Nginx then caching of the files' metadata (not the actual files' contents) can save some latency.

open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

SSL Cache

Enable SSL cache for SSL sessions resumption, so that sub sequent SSL/TLS connection handshakes can be shortened and reduce total SSL overhead.

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

Upstream Keepalive

Enable the upstream connection cache for better reuse of connections to upstream servers. Source.

upstream backend {
    server 127.0.0.1:8080;
    keepalive 32;
}

server {
    ...
    location /api/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

Monitoring

The Stub Status, which is not built by default, is a very simple to setup module but only provide basic status of Nginx.

location /status {
    stub_status on;
    access_log off;
}

It provides the following status for the whole Nginx server in plain text(!) format:

  • Client connections: accepted, handled, active (includes reading, writing and waiting).
  • Total number of client requests.

[Shameless Plug] A better way to capture Nginx status can be added by using Luameter which is a bit more complicated to setup and required the Nginx Lua module (which is awesome). It provides following metrics for each configurable group as a JSON API:

  • Total number of requests / responses.
  • Total number of responses groupped by status code: 1xx, 2xx, 3xx, 4xx, 5xx.
  • Total bytes received from / sent to client.
  • Sampled latency snapshot for estimation of: mean, max, median, 99th percentile, etc., latency.
  • Moving average rate of requests for easier monitoring and predicting.
  • And some more.

Here is a sample dashboard built with Luameter's metrics.

ngxtop is also a good way to check for Nginx status and checking / troubleshooting a live server.

Security

Enable Basic Authentication

You will need a user password file somewhere first.

name:{PLAIN}plain-text-password

Then add below config to server/location block that need to be protected.

auth_basic "This is Protected";
auth_basic_user_file /path/to/password-file;

Only Allow Access From Localhost

location /local {
    allow 127.0.0.1;
    deny all;
    ...
}

Secure SSL settings

# don’t use SSLv3 ref: POODLE CVE-2014-356 - http://nginx.com/blog/nginx-poodle-ssl/
ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;  

# Ciphers set to best allow protection from Beast, while providing forwarding secrecy, as defined by Mozilla (Intermediate Set) - https://wiki.mozilla.org/Security/Server_Side_TLS#Nginx
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
ssl_prefer_server_ciphers  on;

Miscellaneous

Sub-Request Upon Completion

There are some cases that you want to pass the request to another backend in addition to and after serving it. One use case is to track the number of completed downloads by calling an API after user completed download a file. Another use case is for tracking request where you want to return as fast as possible (perhaps with an empty_gif) and then do the actual recording in background. The post_action that allows you to define a sub-request that will be fired upon completion of the current request are perfect solution for these use cases.

location = /empty.gif {
    empty_gif;
    expires -1;
    post_action @track; 
}

location @track {
    internal;
    proxy_pass http://tracking-backend;
}

Enable Cross Origin Resource Sharing

Simple, wide-open configuration to allow cross-domain requests to your server.

location ~* \.(eot|ttf|woff) {
    add_header Access-Control-Allow-Origin *;
}

Links

Some other awesome resources for configuring Nginx: