Comprehensive Guide: Key Interview Points for High-Paying Linux Cloud Computing Positions on Nginx (Includes Standard Answers and Scripts)

To help everyone better prepare for Nginx-related questions in interviews for Linux cloud computing positions, I have compiled 30 frequently asked interview questions covering various aspects from basic concepts to advanced applications. The questions are arranged in order of difficulty and marked with core examination points, allowing everyone to check their knowledge mastery.

The table below summarizes all interview questions for a quick overview.

Difficulty Level Question Core Points
Beginner 1. Please explain what Nginx is? Basic Concept
2. What are the main differences between Nginx and Apache? Understanding Technical Choices
3. List some of the main features or advantages of Nginx. Core Features
4. What are some common Nginx commands (such as start, stop, reload configuration)? Basic Operations
5. What is the default path for the Nginx configuration file? Configuration File Basics
6. What is the directive used to set the number of Nginx worker processes? Core Configuration Directive
7. What is the directive used to configure virtual hosts (server blocks) in Nginx? Server Block Configuration
8. How do you set Nginx to listen on a specific port (e.g., port 80)? Basic Network Configuration
9. Please explain what a forward proxy and a reverse proxy are? Proxy Concepts
10. What type of proxy is Nginx primarily used for? (Reverse Proxy) Role Identification
Intermediate 11. Please elaborate on the Master/Worker process model of Nginx and its working principle. Architectural Principles
12. How does Nginx handle an HTTP request? Request Handling Process
13. What is the matching priority order of the <span>location</span> directive in Nginx? Configuration Priority
14. How do you configure a simple reverse proxy in Nginx to forward requests to a backend application server? Reverse Proxy Configuration
15. What are some common algorithms used in Nginx load balancing? Load Balancing Algorithms
16. How do you configure a load balancing upstream server group named <span>backend</span> in Nginx? Load Balancing Configuration
17. Please explain the difference between the <span>root</span> and <span>alias</span> directives in Nginx when configuring static resources. Static Resource Path
18. How do you configure Nginx to achieve separation of dynamic and static content? What are the benefits of doing so? Dynamic and Static Separation
19. How do you configure Nginx to support WebSocket protocol reverse proxy? Special Protocol Support
20. In Nginx, how do you set Gzip compression to reduce network transmission? Performance Optimization
21. For a single-page application (SPA) using History routing mode, how do you resolve a 404 error when refreshing on Nginx? Frontend Routing Adaptation
22. How do you configure Nginx to solve frontend cross-origin issues (CORS)? Cross-Origin Issues
23. How do you configure Nginx to implement a caching strategy for frontend static resources (e.g., Hash resource permanent caching)? Caching Strategy
24. What is the difference between adding a trailing slash and not adding a trailing slash to the <span>proxy_pass</span> directive path in Nginx? Proxy Path Details
Advanced 25. How do you optimize Nginx to support a higher number of concurrent connections and improve performance? High Performance Optimization
26. Explain the role of the <span>try_files</span> directive in Nginx and provide a common application example. Request Rewriting and Fallback
27. How do you configure Nginx to support HTTPS and force HTTP requests to redirect to HTTPS? Security and HTTPS
28. In Nginx, how do you implement access restrictions (e.g., connection limits, request rates)? Access Control and Security
29. How do you troubleshoot and resolve common Nginx error status codes, such as 502 Bad Gateway and 504 Gateway Timeout? Troubleshooting
30. How do you implement a high availability solution for Nginx? High Availability Architecture

Beginner Difficulty Questions

1. Please explain what Nginx is?

Poor Answer Example:Nginx is a web server that can be used to host websites.

Why This Answer is Poor:This answer is too simplistic and vague, failing to reflect Nginx’s core features and various uses, making it seem unprofessional.

Bonus Answer Example:Nginx is a high-performance, open-source HTTP and reverse proxy server, which can also serve as a mail proxy server and a general TCP/UDP proxy server. Its characteristics include low memory usage, strong concurrency capabilities, and an event-driven asynchronous non-blocking processing model, allowing it to support extremely high concurrent connections. In practical applications, Nginx is commonly used for static content delivery, load balancing, reverse proxying, and API gateway scenarios.

2. What are the main differences between Nginx and Apache?

Poor Answer Example:Nginx is faster than Apache, and Apache is older.

Why This Answer is Poor:This answer is too one-sided and lacks specific technical comparisons, showing a lack of deep understanding.

Bonus Answer Example:The main differences between Nginx and Apache are reflected in the following aspects:

  1. Architectural Model: Apache uses a multi-process/multi-thread model, where each connection corresponds to a process/thread, consuming more resources under high concurrency; Nginx uses an event-driven asynchronous non-blocking model, allowing a single process to handle a large number of concurrent connections.

  2. Resource Consumption: Nginx typically consumes less memory and CPU than Apache, especially in high concurrency scenarios.

  3. Static Content Handling: Nginx performs better in handling static content; Apache has more module support for dynamic content.

  4. Configuration Method: Apache supports .htaccess distributed configuration; Nginx does not support .htaccess but has better performance with centralized configuration.

  5. Module System: Apache’s modules can be dynamically loaded at runtime; Nginx’s modules need to be integrated at compile time.

3. List some of the main features or advantages of Nginx.

Poor Answer Example:Nginx is fast and easy to configure.

Why This Answer is Poor:This answer is too simplistic and does not demonstrate a comprehensive understanding of Nginx’s features.

Bonus Answer Example:The main features and advantages of Nginx include:

  1. High Concurrency and High Performance: Adopting an event-driven asynchronous non-blocking architecture, it can support tens of thousands or even hundreds of thousands of concurrent connections.

  2. Low Memory Consumption: Extremely low memory consumption when handling static content.

  3. Reverse Proxy and Load Balancing: Built-in powerful reverse proxy and various load balancing algorithms.

  4. Hot Deployment: Supports smooth upgrades and configuration reloads without downtime.

  5. High Scalability: Modular architecture supports custom module development.

  6. High Reliability: Excellent stability, capable of running 24/7.

4. What are some common Nginx commands?

Poor Answer Example:nginx -s reload, I can’t remember the others.

Why This Answer is Poor:This answer is incomplete and shows a lack of familiarity with daily operations.

Bonus Answer Example:Common Nginx commands include:

# Start Nginx
nginx

# Quick stop
nginx -s stop

# Graceful stop (after completing current requests)
nginx -s quit

# Reload configuration file
nginx -s reload

# Reopen log files
nginx -s reopen

# Test configuration file syntax
nginx -t

# Specify configuration file
nginx -c /path/to/nginx.conf

5. What is the default path for the Nginx configuration file?

Poor Answer Example:I think it’s in the /etc directory.

Why This Answer is Poor:This answer is uncertain and shows a lack of experience.

Bonus Answer Example:The default paths for the Nginx configuration file typically include:

  • Main configuration file:<span>/etc/nginx/nginx.conf</span>
  • Additional configuration file directory:<span>/etc/nginx/conf.d/</span>
  • Site available configuration:<span>/etc/nginx/sites-available/</span>
  • Enabled site configuration:<span>/etc/nginx/sites-enabled/</span>
  • Default site root directory:<span>/usr/share/nginx/html</span> or <span>/var/www/html</span>

The paths may vary slightly between different Linux distributions, and you can check the actual configuration file path using the <span>nginx -t</span> command.

6. What is the directive used to set the number of Nginx worker processes?

Poor Answer Example:worker_processes, set it to the number of CPU cores.

Why This Answer is Poor:While the answer is correct, it lacks in-depth explanation.

Bonus Answer Example:The directive used to set the number of Nginx worker processes is <span>worker_processes</span>, typically configured in the main context of nginx.conf.

# Set to auto to automatically detect the number of CPU cores
worker_processes auto;

# Or specify a number explicitly
worker_processes 4;

The best practice is to set it to the number of CPU cores or auto, while considering the workload characteristics and system resources. For CPU-intensive tasks, it can be set to the number of CPU cores; for I/O-intensive tasks, the number of processes can be increased appropriately.

7. What is the directive used to configure virtual hosts in Nginx?

Poor Answer Example:server directive.

Why This Answer is Poor:The answer is correct but too simplistic, lacking demonstration of actual configuration capability.

Bonus Answer Example:In Nginx, virtual hosts are configured through the <span>server</span> directive block, with each server block representing a virtual host:

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Multiple server blocks can be defined in the same configuration file, and Nginx will match the corresponding virtual host based on the Host header of the request.

8. How do you set Nginx to listen on a specific port?

Poor Answer Example:Write listen 80 in the server block.

Why This Answer is Poor:The answer is incomplete and does not cover other important configurations.

Bonus Answer Example:Use the <span>listen</span> directive to set the port that Nginx listens on:

server {
    # Listen on port 80, IPv4 and IPv6
    listen 80;
    listen [::]:80;

    # Listen on a specific IP's port
    listen 192.168.1.100:8080;

    # Listen on HTTPS port
    listen 443 ssl;

    server_name example.com;
}

You can also specify additional parameters, such as <span>default_server</span> to set the default server, and <span>ssl</span> to enable SSL, etc.

9. Please explain what a forward proxy and a reverse proxy are?

Poor Answer Example:A forward proxy proxies the client, while a reverse proxy proxies the server side.

Why This Answer is Poor:Although the concept is correct, the explanation is too simple and does not describe practical application scenarios.

Bonus Answer Example:A forward proxy proxies requests initiated by the client, with the client being aware of the proxy’s existence. Typical application scenarios include:

  • Internet behavior management in corporate networks
  • Bypassing restrictions to access external resources
  • Cache acceleration

A reverse proxy receives requests on behalf of the server side, with the client unaware of the existence of the backend real server. Typical application scenarios include:

  • Load balancing
  • Dynamic and static separation
  • Security protection
  • Cache acceleration

Key difference: A forward proxy hides the client’s identity, while a reverse proxy hides the server’s identity.

10. What type of proxy is Nginx primarily used for?

Poor Answer Example:Reverse proxy.

Why This Answer is Poor:Although the answer is correct, it is not comprehensive enough.

Bonus Answer Example:Nginx is primarily used as a reverse proxy, which is one of its core and most widely used functions. Through reverse proxying, Nginx can achieve:

  1. Load Balancing: Distributing requests to multiple backend servers
  2. High Availability: Automatically switching when backend servers fail
  3. SSL Termination: Handling SSL encryption and decryption at the Nginx level
  4. Cache Acceleration: Caching backend responses to improve performance
  5. Security Protection: Hiding backend server information and providing basic security protection

Although Nginx can also be configured as a forward proxy, this is not its primary design purpose.

Intermediate Difficulty Questions

11. Please elaborate on the Master/Worker process model of Nginx and its working principle.

Poor Answer Example:There is one master process and multiple worker processes, and the worker handles requests.

Why This Answer is Poor:This is overly simplified and does not reflect the advantages and working principles of this architecture.

Bonus Answer Example:Nginx adopts a Master-Worker multi-process model:

  • Master Process: Runs with root privileges and is responsible for managing Worker processes, including:

    • Reading and validating configurations
    • Starting and terminating Worker processes
    • Smooth upgrades
    • Reopening log files
  • Worker Processes: Run with normal user privileges and actually handle requests:

    • Each Worker is an independent process
    • Uses an event-driven asynchronous non-blocking I/O model
    • Can handle thousands of concurrent connections

Working Principle:

  1. The Master process binds to privileged ports like 80/443
  2. The Worker processes listen on the same ports through shared sockets
  3. When a new connection arrives, all Workers compete for the accept mutex through atomic operations
  4. The Worker that obtains the mutex handles the connection
  5. Workers efficiently handle multiple connections using event mechanisms like epoll/kqueue

The advantages of this architecture: high concurrency, hot deployment, and fault isolation.

12. How does Nginx handle an HTTP request?

Poor Answer Example:It receives the request and then returns a response.

Why This Answer is Poor:This does not describe the internal request handling process of Nginx.

Bonus Answer Example:The complete process of Nginx handling an HTTP request is as follows:

  1. Parsing Stage:

  • Parsing the request line (method, URI, protocol version)
  • Parsing the request headers
  • Building the request structure
  • Request Rewriting Stage:

    • Executing rules from the rewrite module
    • URL rewriting and redirection
  • Access Control Stage:

    • Executing permission checks from the access module
    • IP black/white list validation
  • Content Generation Stage:

    • Matching location blocks
    • Executing corresponding handlers (static files, proxy, FastCGI, etc.)
  • Logging Stage:

    • Logging access logs
    • Logging error logs (if any errors occur)

    The entire process adopts a pipeline approach, with various modules intervening at appropriate stages to ensure high performance and flexibility.

    13. What is the matching priority order of the <span>location</span> directive in Nginx?

    Poor Answer Example:Exact match has priority, followed by regular expression match.

    Why This Answer is Poor:This is incomplete and inaccurate, lacking specific priority order.

    Bonus Answer Example:The matching priority order of the location directive in Nginx from high to low is:

    1. <span>=</span> Exact Match: <span>location = /path</span>, used immediately when fully matched
    2. <span>^~</span> Prefix Match: <span>location ^~ /prefix</span>, once matched, no further regex checks are performed
    3. <span>~</span> and <span>~*</span> Regular Expression Match: <span>location ~ \.php$</span>, matched in configuration order
    4. General Prefix Match: <span>location /prefix</span>, longest match takes priority
    server {
        location = / {            # 1. Exact match /
            # Handle root request
        }
    
        location ^~ /static/ {    # 2. Prefix match, prioritized over regex
            # Handle static files
        }
    
        location ~ \.php$ {       # 3. Regex match for PHP files
            # Handle PHP requests
        }
    
        location / {              # 4. General prefix match
            # Handle other requests
        }
    }
    

    14. How do you configure a simple reverse proxy in Nginx?

    Poor Answer Example:

    location / {
        proxy_pass http://backend;
    }
    

    Why This Answer is Poor:The configuration is too simple and lacks necessary proxy parameter settings.

    Bonus Answer Example:A complete reverse proxy configuration should include necessary proxy header settings and timeout configurations:

    location /api/ {
        # Backend server address
        proxy_pass http://backend_server;
    
        # Set proxy headers
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    
        # Timeout settings
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    
        # Other proxy settings
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
    
    # Upstream server definition
    upstream backend_server {
        server 192.168.1.10:8080;
        server 192.168.1.11:8080;
    }
    

    15. What are some common algorithms used in Nginx load balancing?

    Poor Answer Example:Round-robin and IP hash.

    Why This Answer is Poor:This answer is incomplete and lacks explanations of the applicable scenarios for various algorithms.

    Bonus Answer Example:Nginx supports multiple load balancing algorithms:

    1. Round Robin: Default algorithm, distributes requests in order
    2. Weighted Round Robin: Distributes based on server weights
    3. IP Hash: Distributes based on client IP, ensuring the same client accesses the same server
    4. Least Connections: Sends requests to the server with the fewest current connections
    5. URL Hash: Distributes based on request URL hash
    6. Fair: Distributes based on server response time (requires third-party module)
    upstream backend {
        # Weighted round robin
        server backend1.example.com weight=3;
        server backend2.example.com weight=2;
    
        # Least connections
        least_conn;
    
        # Or IP hash
        # ip_hash;
    }
    

    The selection strategy should be based on business characteristics: use ip_hash for session persistence, least_conn for performance balancing, and round robin for general needs.

    16. How do you configure a load balancing upstream server group in Nginx?

    Poor Answer Example:

    upstream myapp {
        server 1.1.1.1;
        server 2.2.2.2;
    }
    

    Why This Answer is Poor:The configuration is too basic and does not demonstrate advanced features like health checks.

    Bonus Answer Example:A complete load balancing configuration should include health checks and various parameters:

    upstream backend_cluster {
        # Load balancing algorithm
        least_conn;
    
        # Backend servers, can set weights, status, etc.
        server 192.168.1.10:8080 weight=3 max_fails=2 fail_timeout=30s;
        server 192.168.1.11:8080 weight=2 max_fails=2 fail_timeout=30s;
        server 192.168.1.12:8080 weight=1 max_fails=2 fail_timeout=30s backup;
    
        # Session persistence (requires nginx-sticky-module)
        # sticky cookie srv_id expires=1h domain=.example.com path=/;
    }
    
    server {
        location / {
            proxy_pass http://backend_cluster;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
            proxy_connect_timeout 2s;
    
            # Health check (requires nginx_upstream_check_module)
            # check interval=3000 rise=2 fall=5 timeout=1000 type=http;
        }
    }
    

    17. Please explain the difference between the <span>root</span> and <span>alias</span> directives in Nginx.

    Poor Answer Example:Root and alias are both used to set paths, they are similar.

    Why This Answer is Poor:This does not demonstrate an understanding of the important differences between the two.

    Bonus Answer Example:The main difference between <span>root</span> and <span>alias</span> is in how the path mapping works:

    <span>root</span> directive: Appends the URI of the location to the path specified by root

    location /static/ {
        root /var/www/html;
        # Accessing /static/css/style.css 
        # Corresponds to file /var/www/html/static/css/style.css
    }
    

    <span>alias</span> directive: Replaces the path of the location with the path specified by alias

    location /static/ {
        alias /var/www/static/;
        # Accessing /static/css/style.css
        # Corresponds to file /var/www/static/css/style.css
    }
    

    Key difference:<span>root</span> retains the location path, while <span>alias</span> discards the location path. The path for alias should end with a <span>/</span>.

    18. How do you configure Nginx to achieve separation of dynamic and static content?

    Poor Answer Example:Use one location for static files and another for dynamic ones.

    Why This Answer is Poor:This is too vague and does not provide specific configuration examples.

    Bonus Answer Example:Dynamic and static separation is achieved through different location blocks:

    server {
        listen 80;
        server_name example.com;
    
        # Static resources - CSS, JS, images, etc.
        location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|ttf)$ {
            root /var/www/static;
            expires 1y;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
    
        # Dynamic requests - proxy to application server
        location / {
            proxy_pass http://backend_app;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
    
    upstream backend_app {
        server 192.168.1.20:8000;
        server 192.168.1.21:8000;
    }
    

    Benefits:

    • Static resources are handled directly by Nginx, resulting in higher performance
    • Reduces the load on application servers
    • Better caching strategies
    • Improves user experience

    19. How do you configure Nginx to support WebSocket protocol reverse proxy?

    Poor Answer Example:Configure it like a normal proxy.

    Why This Answer is Poor:This does not consider the special nature of the WebSocket protocol.

    Bonus Answer Example:WebSocket proxying requires special header settings:

    location /websocket/ {
        proxy_pass http://websocket_backend;
    
        # Required headers for WebSocket
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    
        # Other proxy settings
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    
        # Extend timeout
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }
    
    upstream websocket_backend {
        server 192.168.1.30:8080;
    }
    

    Key points: Must set <span>Upgrade</span> and <span>Connection</span> headers, and use HTTP/1.1 protocol.

    20. In Nginx, how do you set Gzip compression to reduce network transmission?

    Poor Answer Example:Just turn on gzip.

    Why This Answer is Poor:This is too simple and does not consider various aspects of compression optimization.

    Bonus Answer Example:A complete Gzip compression configuration should include various optimization parameters:

    http {
        gzip on;
        gzip_vary on;
        gzip_min_length 1024;    # Do not compress less than 1k
        gzip_comp_level 6;       # Compression level 1-9
        gzip_types
            text/plain
            text/css
            text/xml
            text/javascript
            application/javascript
            application/xml+rss
            application/json
            image/svg+xml;
        gzip_disable "msie6";    # Disable compression for IE6
    
        # Pre-compression support (optional)
        gzip_static on;
    }
    

    Optimization Suggestions:

    • No need to compress already compressed files like images and PDFs
    • Compression level 6 strikes a balance between compression ratio and CPU consumption
    • Adjust gzip_types based on actual content types

    21. For a single-page application (SPA) using History routing mode, how do you resolve a 404 error when refreshing on Nginx?

    Poor Answer Example:Switch to hash routing.

    Why This Answer is Poor:This does not provide an actual Nginx configuration solution.

    Bonus Answer Example:This is because the URL directly requested by the browser does not exist on the server, and you need to configure Nginx to use try_files to fall back to index.html:

    server {
        listen 80;
        server_name spa.example.com;
        root /var/www/spa;
        index index.html;
    
        location / {
            # Try to find the file by URL, if not found, return index.html
            try_files $uri $uri/ /index.html;
        }
    
        # Static resources handled normally
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }
    

    With this configuration, all frontend routes will be rewritten to index.html, which will be handled by the frontend JavaScript.

    22. How do you configure Nginx to solve frontend cross-origin issues (CORS)?

    Poor Answer Example:Set Access-Control-Allow-Origin to *.

    Why This Answer is Poor:This is too insecure and incomplete.

    Bonus Answer Example:A complete CORS configuration should consider security:

    server {
        listen 80;
        server_name api.example.com;
    
        location / {
            # Allowed source domain
            add_header Access-Control-Allow-Origin "https://www.example.com";
    
            # Allowed request methods
            add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE";
    
            # Allowed request headers
            add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With";
    
            # Allow cookies
            add_header Access-Control-Allow-Credentials "true";
    
            # Preflight request cache time
            add_header Access-Control-Max-Age 3600;
    
            # Handle OPTIONS preflight requests
            if ($request_method = 'OPTIONS') {
                return 204;
            }
    
            # Normal request handling
            proxy_pass http://backend;
        }
    }
    

    Security Considerations:

    • Do not use the <span>*</span> wildcard lightly
    • Clearly specify allowed source domains
    • Set Allow-Credentials as needed

    23. How do you configure Nginx to implement a caching strategy for frontend static resources?

    Poor Answer Example:Set expires 1d.

    Why This Answer is Poor:This is too simple and does not differentiate caching strategies for different types of resources.

    Bonus Answer Example:A reasonable caching strategy should differentiate based on resource types:

    server {
        # Resources with hash values (generated by build tools like webpack) - Permanent cache
        location ~* \.[a-f0-9]{8,}\.(css|js)$ {
            expires 1y;
            add_header Cache-Control "public, immutable, max-age=31536000";
            access_log off;
        }
    
        # Regular static resources - cache for a period
        location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
            expires 30d;
            add_header Cache-Control "public";
            access_log off;
        }
    
        # HTML files - no cache or short-term cache
        location ~* \.html$ {
            expires 5m;
            add_header Cache-Control "public, must-revalidate";
        }
    
        # API interfaces - no cache
        location /api/ {
            proxy_pass http://backend;
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
            expires 0;
        }
    }
    

    24. What is the difference between adding a trailing slash and not adding a trailing slash to the <span>proxy_pass</span> directive path in Nginx?

    Poor Answer Example:One has a slash and the other does not, they are similar.

    Why This Answer is Poor:This does not demonstrate an understanding of this important difference.

    Bonus Answer Example:The trailing slash in the <span>proxy_pass</span> directive has an important impact on URL forwarding:

    **Without adding a trailing slash**:<span>proxy_pass http://backend;</span>: Retains the location path

    location /api/ {
        proxy_pass http://backend;
        # Request /api/users → Forward to http://backend/api/users
    }
    

    **With adding a trailing slash**:<span>proxy_pass http://backend/;</span>: Discards the location path

    location /api/ {
        proxy_pass http://backend/;
        # Request /api/users → Forward to http://backend/users
    }
    

    Practical Applications:

    # Retain prefix
    location /service/ {
        proxy_pass http://backend/service/;
    }
    
    # Remove prefix  
    location /service/ {
        proxy_pass http://backend/;
    }
    
    # Rewrite path
    location /old/ {
        proxy_pass http://backend/new/;
    }
    

    Advanced Difficulty Questions

    25. How do you optimize Nginx to support a higher number of concurrent connections and improve performance?

    Poor Answer Example:Increase worker_processes and worker_connections.

    Why This Answer is Poor:This is superficial and lacks a systematic optimization approach.

    Bonus Answer Example:Nginx performance optimization needs to be approached from multiple levels:

    1. Process and Connection Optimization

    # CPU affinity
    worker_processes auto;
    worker_cpu_affinity auto;
    
    # Maximum connections per worker
    worker_connections 65536;
    
    # Maximum number of open files per worker
    worker_rlimit_nofile 65536;
    

    2. Network Optimization

    # Use epoll event-driven
    use epoll;
    
    # Multi-connection acceptance optimization
    multi_accept on;
    
    # Send timeout and buffer optimization
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;
    

    3. System-Level Optimization

    # Adjust system file descriptor limits
    echo "* soft nofile 65536" >> /etc/security/limits.conf
    echo "* hard nofile 65536" >> /etc/security/limits.conf
    
    # Adjust network parameters
    echo 'net.core.somaxconn = 65536' >> /etc/sysctl.conf
    echo 'net.ipv4.tcp_max_syn_backlog = 65536' >> /etc/sysctl.conf
    

    26. Explain the role of the <span>try_files</span> directive in Nginx and provide a common application example.

    Poor Answer Example:try_files is used to try to find files.

    Why This Answer is Poor:This does not explain the specific role and practical scenarios.

    Bonus Answer Example:The <span>try_files</span> directive checks for the existence of files in order, returning the first found file, and if none exist, it executes the last fallback handling.

    Syntax::<span>try_files file1 file2 ... =code fallback</span>

    Common Applications:

    1. SPA Route Fallback
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    1. Caching Static Resource Service
    location /images/ {
        try_files $uri $uri/ @image_processor;
    }
    
    location @image_processor {
        # Image processing logic
        proxy_pass http://image_backend;
    }
    
    1. Graceful 404 Handling
    location / {
        try_files $uri $uri/ @backend =404;
    }
    
    location @backend {
        proxy_pass http://app_server;
    }
    

    27. How do you configure Nginx to support HTTPS and force HTTP requests to redirect to HTTPS?

    Poor Answer Example:Configure the SSL certificate and then do a 301 redirect.

    Why This Answer is Poor:This lacks specific configuration and security optimizations.

    Bonus Answer Example:A complete HTTPS configuration includes certificate configuration, security hardening, and HTTP redirection:

    # HTTP force redirect to HTTPS
    server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://$server_name$request_uri;
    }
    
    # HTTPS server
    server {
        listen 443 ssl http2;
        server_name example.com www.example.com;
    
        # SSL certificate configuration
        ssl_certificate /etc/ssl/certs/example.com.crt;
        ssl_certificate_key /etc/ssl/private/example.com.key;
    
        # SSL security configuration
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        # HSTS header (force HTTPS)
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    
        # Other security headers
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;
    
        location / {
            root /var/www/html;
            index index.html;
        }
    }
    

    28. In Nginx, how do you implement access restrictions?

    Poor Answer Example:Use limit_req to limit request frequency.

    Why This Answer is Poor:This is incomplete; there are various ways to implement access restrictions.

    Bonus Answer Example:Nginx provides various access restriction mechanisms:

    1. Request Frequency Limiting

    # Define limit zone
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://backend;
    }
    

    2. Concurrent Connection Limiting

    # Define connection limit zone  
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    
    location /download/ {
        limit_conn perip 5;    # Maximum 5 concurrent connections per IP
        limit_rate 500k;       # Limit speed to 500KB/s
    }
    

    3. Geolocation-Based Access Control

    # Requires ngx_http_geoip_module
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    
    location / {
        if ($geoip_country_code != CN) {
            return 403;
        }
    }
    

    4. Basic Authentication

    location /admin/ {
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
    

    29. How do you troubleshoot and resolve common Nginx error status codes?

    Poor Answer Example:Check the error logs.

    Why This Answer is Poor:This is too simple and lacks specific troubleshooting approaches.

    Bonus Answer Example:Common error status code troubleshooting methods:

    502 Bad Gateway

    • Check if the backend service is running normally
    • Check firewall and network connectivity
    • Adjust proxy buffer and timeout settings
    proxy_connect_timeout 60s;
    proxy_read_timeout 60s;
    proxy_send_timeout 60s;
    

    504 Gateway Timeout

    • Increase proxy timeout
    • Check backend service performance
    • Optimize backend processing logic

    413 Request Entity Too Large

    client_max_body_size 100m;
    

    499 Client Closed Request

    • Client timeout, check client network and timeout settings
    • Optimize server response time

    General Troubleshooting Steps:

    1. Check Nginx error logs:<span>tail -f /var/log/nginx/error.log</span>
    2. Test configuration file:<span>nginx -t</span>
    3. Check system resources:<span>top</span>, <span>free -m</span>, <span>df -h</span>
    4. Network connectivity tests:<span>telnet</span>, <span>curl</span>

    30. How do you implement a high availability solution for Nginx?

    Poor Answer Example:Use Keepalived for dual-machine hot backup.

    Why This Answer is Poor:This is a single solution and does not consider modern cloud-native environments.

    Bonus Answer Example:There are multiple implementation solutions for Nginx high availability:

    1. Traditional Keepalived Solution

    # Keepalived configuration example
    vrrp_script chk_nginx {
        script "pidof nginx"
        interval 2
        weight 2
    }
    
    vrrp_instance VI_1 {
        state MASTER
        interface eth0
        virtual_router_id 51
        priority 100
        virtual_ipaddress {
            192.168.1.100
        }
        track_script {
            chk_nginx
        }
    }
    

    2. DNS Round Robin + Health Checks

    • Multiple Nginx instances configured with the same DNS
    • Use third-party health check services
    • Automatically exclude faulty nodes

    3. Cloud Load Balancers

    • AWS ALB/NLB, GCP Load Balancer
    • Alibaba Cloud SLB, Tencent Cloud CLB
    • Auto-scaling and health checks

    4. Kubernetes Ingress

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: nginx-ingress
    spec:
      rules:
      - host: example.com
        http:
          paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web-service
                port:
                  number: 80
    

    Selection Criteria: Business scale, technology stack, operational capabilities, cost budget.

    Summary

    Mastering these Nginx interview questions not only helps in passing technical interviews but is also crucial for better configuration, optimization, and troubleshooting in actual work. It is recommended to practice hands-on while understanding the theory to accumulate practical experience.

    The road is long and learning is endless. May every time you run <span>nginx -t</span><code><span> return </span><code><span>syntax is ok</span>!

    Leave a Comment