> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/ask/flat/chapter-38-web-servers/di-38.2-jie-nginx-web-fu-wu-qi.md).

# 38.2 Nginx Web Server

Nginx employs an event-driven asynchronous architecture with a multi-process single-threaded worker model, achieving high concurrency handling with low memory consumption. This section covers installation via pkg and basic configuration.

## Installing Nginx

Install Nginx using the pkg package manager:

```sh
# pkg install nginx
```

Install Nginx using Ports:

```sh
# cd /usr/ports/www/nginx/
# make install clean
```

### Finding Related Packages

In addition to the main program, the system provides multiple Nginx-related packages, which can be retrieved in the following ways.

Use the pkg command to quickly search for Nginx-related packages:

```sh
$ pkg search -o nginx
```

You can also find Nginx-related packages in the Ports directory; this method is suitable for scenarios where you need to view the source code:

```sh
$ ls /usr/ports/www/ | grep nginx
```

## Daemon

To ensure Nginx starts automatically at boot, first configure it as an enabled service, then manually start the service for testing.

Set the Nginx service to start automatically at system boot:

```sh
# service nginx enable
nginx enabled in /etc/rc.conf
```

Start the Nginx service; the system will automatically check the configuration file syntax before starting:

```sh
# service nginx start
Performing sanity check on nginx configuration:
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
Starting nginx.
```

You can use the following command to view the IPv4 network connections and ports that Nginx is listening on; this method effectively verifies the service running status:

```sh
# sockstat -4 | grep nginx
www      nginx       1154 6   tcp4   *:80                  *:*
root     nginx       1153 6   tcp4   *:80                  *:*
```

## Browsing Web Pages

After confirming that the Nginx service is running normally, you can verify the web server through a browser.

Open `localhost` in the local browser, or access using the server IP address, for example `http://192.168.179.150/`:

> **Tip**
>
> The **192.168.179.150** in the above example is a placeholder and needs to be replaced with the actual value.

![Nginx FreeBSD](/files/qiLdhFDqMXnh1sCzJEl0)

## Configuration Files

Nginx configuration is flexible, employing a modular structural design; for detailed configuration methods, please refer to the official documentation. This section only briefly explains how to start Nginx on FreeBSD and the location and usage of its configuration files.

For configuration tutorials, please refer to the [official documentation](https://nginx.org/en/docs/).

On FreeBSD, Nginx configuration files are located in the **/usr/local/etc/nginx/** directory, with the main configuration file being **/usr/local/etc/nginx/nginx.conf**, which is organized in a hierarchical structure.

Directory structure:

```sh
/usr/local/
├── etc/
│   └── nginx/
│       ├── nginx.conf          # Nginx main configuration file
│       └── mime.types          # MIME type definition file
└── www/
    └── nginx/                  # Nginx site root directory
```

In the default configuration, the Nginx site root directory is **/usr/local/www/nginx/**. To change the site root directory, in the **/usr/local/etc/nginx/nginx.conf** file, change

```nginx
root	/usr/local/www/nginx;
```

to the actual directory path needed, for example `root /path/to/new/webroot;`. After modifying the configuration, you need to restart the service for changes to take effect.

### Sample Configuration File (Nginx + Typecho Pseudo-static + SSL)

To facilitate understanding of Nginx configuration, the following provides a complete sample configuration file, including Nginx, Typecho pseudo-static rules, and SSL configuration.

```nginx
user  www;									 	# Specify the Nginx runtime user (default uses compile-time settings)

worker_processes  auto;                          # Automatically set the number of worker processes based on CPU cores (modern recommendation)

# Error log path (uncomment if needed)
#error_log  /var/log/nginx/error.log;

# Master process PID file
#pid        logs/nginx.pid;


events {                                         # events module configuration begins
    worker_connections  10240;                   # Maximum number of connections per worker process (improves concurrency)
}                                                # events module ends


http {                                           # http module configuration begins
    include       mime.types;                    # Include MIME type definition file
    default_type  application/octet-stream;      # Default MIME type

    sendfile on;                                 # Enable sendfile to improve file transfer efficiency
    tcp_nopush on;                               # Optimize packet sending (works with sendfile)
    tcp_nodelay on;                              # Reduce latency (send small packets immediately)

    keepalive_timeout 65;                        # Keepalive timeout (seconds)
    types_hash_max_size 2048;                    # MIME type hash table size optimization

    server_tokens off;                           # Hide Nginx version number (security)


    # ========================
    # HTTP virtual host
    # ========================
    server {
        listen 80;                               # Listen on port 80
        server_name localhost;                   # Virtual host name

        root /usr/local/www/nginx;               # Website root directory
        index index.php index.html;              # Default index file order (PHP first)

        location / {                             # Root path matching
            try_files $uri $uri/ /index.php?$query_string; # Alternative to if + rewrite
        }

        location ~ \.php$ {                      # Match PHP requests (more precise)
            include fastcgi_params;              # Include FastCGI parameters
            fastcgi_pass 127.0.0.1:9000;         # FastCGI service address (PHP-FPM)

            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # Correct PHP script path (key optimization)
            fastcgi_index index.php;             # Default FastCGI index file
        }

        location ~ /\. {                         # Deny access to hidden files (e.g., .htaccess)
            deny all;
        }

        error_page 500 502 503 504 /50x.html;    # Define 5xx error pages
        location = /50x.html {                   # Exact match for error page
            root /usr/local/www/nginx-dist;      # Error page directory
        }
    }


    # ========================
    # HTTPS virtual host
    # ========================
    server {
        listen 443 ssl;                          # Enable HTTPS
        http2 on;                                 # Enable HTTP/2 (recommended syntax for Nginx 1.25.1+)
        # The old syntax listen 443 ssl http2 is deprecated, see Nginx. Module ngx_http_v2_module[EB/OL]. [2026-04-16]. <https://nginx.org/en/docs/http/ngx_http_v2_module.html>
        server_name localhost;                   # Virtual host name

        root /usr/local/www/nginx-dist;          # HTTPS website root directory
        index index.php index.html;              # Default index file

        ssl_certificate     /usr/local/etc/nginx/fbxs.crt; # SSL certificate path
        ssl_certificate_key /usr/local/etc/nginx/fbxs.key; # SSL private key path

        ssl_protocols TLSv1.2 TLSv1.3;           # Enable modern TLS protocols
        ssl_ciphers HIGH:!aNULL:!MD5;            # Use secure cipher suites (avoid outdated algorithms)

        ssl_session_timeout 1d;                  # SSL session cache duration
        ssl_session_cache shared:SSL:10m;        # Shared SSL session cache

        # Basic security headers (recommended for modern web)
        add_header X-Frame-Options SAMEORIGIN;   # Prevent embedding in iframes (clickjacking)
        add_header X-Content-Type-Options nosniff; # Disable MIME sniffing
        add_header X-XSS-Protection "1; mode=block"; # Browser XSS protection

        # Optional: Enable HSTS (force HTTPS)
        #add_header Strict-Transport-Security "max-age=31536000" always;

        location / {                             # Root path matching
            try_files $uri $uri/ /index.php?$query_string; # Unified entry (recommended for modern frameworks)
        }

        location ~ \.php$ {                      # PHP handling under HTTPS
            include fastcgi_params;              # Include FastCGI parameters
            fastcgi_pass 127.0.0.1:9000;         # FastCGI service address

            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # Correct script path
            fastcgi_index index.php;             # Default index file
        }

        location ~ /\. {                         # Deny access to hidden files
            deny all;
        }
    }

}                                                # http module ends
```

## References

* FreeBSD Project. nginx -- HTTP and reverse proxy server, mail proxy server\[EB/OL]. \[2026-04-14]. <https://man.freebsd.org/cgi/man.cgi?query=nginx&sektion=8>. Nginx server manual page, describing startup options and signal handling.
* Nginx, Inc. Nginx Documentation\[EB/OL]. \[2026-04-14]. <https://nginx.org/en/docs/>. Official Nginx documentation, covering configuration directives, modules, and performance tuning.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.bsdcn.org/ask/flat/chapter-38-web-servers/di-38.2-jie-nginx-web-fu-wu-qi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
