【问题标题】:nginx: Redirect to index.html if a given URI points to an existing directorynginx:如果给定的 URI 指向现有目录,则重定向到 index.html
【发布时间】:2013-06-12 08:04:07
【问题描述】:

假设用户在浏览器中输入http://mysite.com/css。如果 URI(在这种情况下为 css)是服务器根目录中存在的目录,我想重定向到 index.html。要查看它的实际效果,处理请求后,地址栏中的 URL 应保持原样(例如 http://mysite.com/css),但会提供 index.html 的内容,而不是显示目录的结构。

这是我尝试过的。请注意,/login/share 不是我的服务器根目录中的目录或文件。 /php/login.php/php/share.php 仅存在重写规则。

location / {
    try_files $uri $uri/ /index.html;
}

location = /css {
    # redirects to index.html, but removes css from URL,
    # i.e. http://mydomain.com/css -> http://mydomain.com
    rewrite ^(.+)$ /index.html/css break;
}

location = /php {
    rewrite ^(.+)$ /index.html/php break;
}

location ^~ /login/ {
    rewrite ^/login/(.+)$ /php/login.php?url=$1 last;
}

location ^~ /share/ {
    rewrite ^/share/(.+)$ /php/share.php?url=$1 last;
}

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

    # With php5-cgi alone:
    #fastcgi_pass 127.0.0.1:9000;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

我的服务器根目录中有两个目录cssjs。使用此配置,对http://mydomain.com/csshttp://mydomain.com/php 的请求将重定向到http://mydomain.com。这很好,但是 URI 被丢弃了。我该怎么做?

我也很好奇如何概括服务器根目录中任意数量目录的行为。我可能需要使用if 来检查请求的URI 是否是目录,但是我一遍又一遍地read 必须尽可能避免if。我猜,对于只有 2 个目录,有单独的位置块应该更有效?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    我的代码有错误...现在修复它后,'http://mydomain.com/css' 提供来自 index.html 的内容。我在正则表达式中使用& 而不是$...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2020-07-17
      • 2014-03-09
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      相关资源
      最近更新 更多