首页 > 解决方案 > 在不更改前端代码的情况下禁用哈希 URL(如 http://localhost/#/login)

问题描述

我想禁用哈希 URL(如http://localhost/#/login)但我无法更改前端代码。我可以通过其他方式(如 Nginx 或 Apache Config)解决它吗?

标签: apachenginxreact-routerfrontendrouter

解决方案


  1. 它可以重定向#/foo本演示中的哈希 URL https://jsfiddle.net/yaoyuan/exLwhy57/1/

  2. 安装 Nginx。在 Mac 上使用https://github.com/denji/homebrew-nginx

  3. 为 Mac 安装 Nginx 模块 https://denji.github.io/homebrew-nginx/#modules brew reinstall nginx-full --with-sub-module; 然后我们可以使用 sub_filter 表达式 https://nginx.org/en/docs/http/ngx_http_sub_module.html

  4. 删除demo1中的js代码,得到demo2 https://jsfiddle.net/yaoyuan/exLwhy57/2/

  5. 使用这个 nginx 配置
location / {
     root   html; (use your folder)
     index  index.html index.htm;
     sub_filter </head>
          '</head><script>
           function redirect() {
             if (location.hash === "#/foo") {
                 window.location.replace("https://example.com");
              }
            }
            window.onhashchange = function() {
                if (location.hash === "#/foo") {
                    window.location.replace("https://example.com");
                }
            }
            redirect();
            </script>';
            sub_filter_once on;        
  }
  1. 运行nginx -c nginx.config以使用此配置

我们可以在 HTML 中找到一个新的片段,然后我们解决这个问题。


推荐阅读