search
HomeOperation and MaintenanceNginxHow does Nginx solve the 404 problem of page refresh in history mode?

    Pre-knowledge

    • Single page application (SPA - single page application)
      Only load the page for the first time When, the only HTML page and its public static resources are returned, and subsequent page jumps will not fetch the HTML file from the server. (Hash and history routing implement browser url changes without refreshing the page)

    • hash routing
      Example: www.baidu.com/#/home, originally hash is used to combine The anchor point realizes the control of the page view. When the value after # changes, the page will not be re-requested. This is mainly achieved through the onhashchange method of the window.

    • history routing
      Compared with hash routing, the most intuitive change is that there is no # in the routing. By calling a series of methods on the window.history object, the page is not refreshed. Jump(pushState, replaceState).

    In history mode, because the url has changed, if you refresh the page manually at this time, the browser thinks it is requesting a new page (initiating a new Http request), and the new page is Does not exist (if the backend is not configured), resulting in 404.

    Let’s briefly describe what happens after entering the IP or domain name on the browser (it feels a bit like an interview question????). After pressing Enter, the http sent by the browser will request html. After a series of forwarding and addressing parsing, the file is received by port 80 (default) on the server where the target IP is located. At this time, the problem arises. After the server's 80 interface receives the HTTP request, it does not know what to do. To return something, this time you need Nginx to perform static resource proxy and tell the server what static files to return

    Nginx

    For general project deployment, we need to deal with nginx. conf configuration file
    What you need to know about this file is as follows

       ....
       # http 是指令块,针对http网络传输的一些指令配置
       http {
           #文件扩展名与文件类型映射表 
           include mime.types;
           #设置客户端与服务端请求的超时时间
           keepalive_timeout  65;
           # 开启压缩功能,目的:提高传输效率,节省带宽 
           gzip on
           server {
              #监听端口
              listen   80;
              #服务命名,最好就是用这个服务器的域名命名
              server_name localhost;
              #指令块,配置外部访问资源和实际资源的对应关系
              location /{
                  root /usr/blog; #表示静态资源所在的目录
                  index  index.html index.htm; #访问这个路径对应的默认静态资源文件或者网页
              }
           }
       }

    location

    Syntax

       location [=|~|~*|^~|@] uri { ... } 
       location @name { ... }
    • =: indicates exact match

    • ~: Indicates case-sensitive regular matching

    • ~*: Indicates case-insensitive regular matching

    • ^~: Indicates that the URI starts with a regular string

    • !~: Indicates case-sensitive regular expression mismatch

    • !~*: Indicates case-insensitive regular non-matching

    • /: Universal matching, any request will be matched to

    Common matching rules

       # 将所有请求直接转发给服务器的9090端口
        location = / {
          proxy_pass http://127.0.0.1:9090/;
        }
        # 目录匹配 
        location ^~ /static/ { 
            root /webroot/static/;
        } 
        # 后缀匹配 
        location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ { 
            root /webroot/res/; 
        }
        # 将/account/开始的请求转发给Account服务器
        location /account/ {
            proxy_pass http://127.0.0.1:8080/
        }
        # 将/order/开始的请求转发给Order服务器
        location /order/ {
            proxy_pass http://127.0.0.1:9090/
        }

    root and alias

    The difference between the two is how nginx interprets the url after location

    [root]
    Syntax: root path
    Default value: root html
    Configuration section: http, server, location, if
    Processing result: root path + location path

    [alias]
    Syntax: alias path
    Configuration section :location
    Processing results: Use alias path to replace location path

       # 返回/www/root/html/t/a.html的文件
       location ^~ /t/ { 
           root /www/root/html/;
       } 
       # 返回/www/root/html/new_t/a.html的文件 
       # 把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。 
       location ^~ /t/ { 
           alias /www/root/html/new_t/; 
       }

    Solve the problem of 404 after refreshing

    It can be known from the above knowledge that after refreshing, the browser will The current url requests the html file, but SPA only has one html file, so you need to configure a line of code in the corresponding location of nginx.conf try_files $uri $uri/ /index.html; Tell nginx if in order Check whether the file exists, if not, redirect to the index.html file

    The above is the detailed content of How does Nginx solve the 404 problem of page refresh in history mode?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    NGINX: The Versatile Tool for Modern Web ApplicationsNGINX: The Versatile Tool for Modern Web ApplicationsApr 11, 2025 am 12:03 AM

    NGINXisessentialformodernwebapplicationsduetoitsrolesasareverseproxy,loadbalancer,andwebserver,offeringhighperformanceandscalability.1)Itactsasareverseproxy,enhancingsecurityandperformancebycachingandloadbalancing.2)NGINXsupportsvariousloadbalancingm

    Nginx SSL/TLS Configuration: Securing Your Website with HTTPSNginx SSL/TLS Configuration: Securing Your Website with HTTPSApr 10, 2025 am 09:38 AM

    To ensure website security through Nginx, the following steps are required: 1. Create a basic configuration, specify the SSL certificate and private key; 2. Optimize the configuration, enable HTTP/2 and OCSPStapling; 3. Debug common errors, such as certificate path and encryption suite issues; 4. Application performance optimization suggestions, such as using Let'sEncrypt and session multiplexing.

    Nginx Interview Questions: Ace Your DevOps/System Admin InterviewNginx Interview Questions: Ace Your DevOps/System Admin InterviewApr 09, 2025 am 12:14 AM

    Nginx is a high-performance HTTP and reverse proxy server that is good at handling high concurrent connections. 1) Basic configuration: listen to the port and provide static file services. 2) Advanced configuration: implement reverse proxy and load balancing. 3) Debugging skills: Check the error log and test the configuration file. 4) Performance optimization: Enable Gzip compression and adjust cache policies.

    Nginx Caching Techniques: Improving Website PerformanceNginx Caching Techniques: Improving Website PerformanceApr 08, 2025 am 12:18 AM

    Nginx cache can significantly improve website performance through the following steps: 1) Define the cache area and set the cache path; 2) Configure the cache validity period; 3) Set different cache policies according to different content; 4) Optimize cache storage and load balancing; 5) Monitor and debug cache effects. Through these methods, Nginx cache can reduce back-end server pressure, improve response speed and user experience.

    Nginx with Docker: Deploying and Scaling Containerized ApplicationsNginx with Docker: Deploying and Scaling Containerized ApplicationsApr 07, 2025 am 12:08 AM

    Using DockerCompose can simplify the deployment and management of Nginx, and scaling through DockerSwarm or Kubernetes is a common practice. 1) Use DockerCompose to define and run Nginx containers, 2) implement cluster management and automatic scaling through DockerSwarm or Kubernetes.

    Advanced Nginx Configuration: Mastering Server Blocks & Reverse ProxyAdvanced Nginx Configuration: Mastering Server Blocks & Reverse ProxyApr 06, 2025 am 12:05 AM

    The advanced configuration of Nginx can be implemented through server blocks and reverse proxy: 1. Server blocks allow multiple websites to be run in one instance, each block is configured independently. 2. The reverse proxy forwards the request to the backend server to realize load balancing and cache acceleration.

    Nginx Performance Tuning: Optimizing for Speed and Low LatencyNginx Performance Tuning: Optimizing for Speed and Low LatencyApr 05, 2025 am 12:08 AM

    Nginx performance tuning can be achieved by adjusting the number of worker processes, connection pool size, enabling Gzip compression and HTTP/2 protocols, and using cache and load balancing. 1. Adjust the number of worker processes and connection pool size: worker_processesauto; events{worker_connections1024;}. 2. Enable Gzip compression and HTTP/2 protocol: http{gzipon;server{listen443sslhttp2;}}. 3. Use cache optimization: http{proxy_cache_path/path/to/cachelevels=1:2k

    Nginx Security Hardening: Protecting Your Web Server From AttacksNginx Security Hardening: Protecting Your Web Server From AttacksApr 04, 2025 am 12:06 AM

    Nginx security enhancement can be achieved through the following steps: 1) Ensure all traffic is transmitted through HTTPS, 2) Configure HTTP headers to enhance communication security, 3) Set up SSL/TLS encrypted data transmission, 4) Implement access control and rate limiting to prevent malicious traffic, 5) Use the ngx_http_secure_link_module module to prevent SQL injection attacks. These measures can effectively improve the security of Nginx servers.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor