Jie*_*eng 15 html5 nginx singlepage
我如何配置nginx来重定向所有的URL(没有前置/api或一些静态资源,例如JS /图像)index.html?原因是我使用HTML5推送状态URL与单页面应用程序.无论是AJAX还是JS,意义内容都会根据URL进行更改
我当前的nginx配置如下:
server {
listen 2000;
server_name localhost;
location / {
root /labs/Projects/Nodebook/public;
index index.html;
}
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:3000/;
proxy_redirect off;
}
}
Run Code Online (Sandbox Code Playgroud)
mat*_*tes 18
location / {
try_files $uri /index.html;
}
Run Code Online (Sandbox Code Playgroud)
这将检查所请求的文件是否存在并将其返回.如果该文件不存在,则返回index.html.
http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
mattes答案几乎是一个解决方案,但它不会像aschepis指出的那样为丢失的文件(例如favicon.icon)提供404.
Nginx将选择匹配的第一个位置.所以我们可以先匹配文件(如果文件不存在,将提供404).之后为所有网址添加了一个默认为index.html的位置.
location /.+\..+ { # files (assuming they always have a dot)
# use eg alias to serve some files here
}
location / { # url routed by client, client gives 404 for bad urls
try_files $uri /index.html;
}
Run Code Online (Sandbox Code Playgroud)
您需要添加到您的 nginx 配置文件中:
rewrite ^(.+)$ /index.html last;
Run Code Online (Sandbox Code Playgroud)
然后假设您正在使用 Backbone.js,只需确保将任何未定义的路由重新路由到 404 页面:
routes: {
// Other routes
"*path" : "notFound"
},
notFound: function(path) {
// Load 404 template, probably of a cute animal.
}
Run Code Online (Sandbox Code Playgroud)
来源: http ://readystate4.com/2012/05/17/nginx-and-apache-rewrite-to-support-html5-pushstate/
| 归档时间: |
|
| 查看次数: |
14316 次 |
| 最近记录: |