nginx伪静态配置

1. .htaccess文件的作用

.htaccess目录访问策略配置文件,放在目录中,作用与当前目录及其子目录。

具体支持:

1. rewrite 重定向路由
2. 设置目录访问权限,允许/禁止
3. 自定义404错误页
4. 改变文件扩展名
5. 文件夹密码保护

2. try_files

try_files是尝试读取文件。

try_files $uri $uri/ @locationName;

上面这个try_files的意思是:

1. $uri是nginx的变量,表示用户访问的url地址,http://www.xxx.com/index.html, 那么$uri就是 /index.html
2. $url/表示访问的是一个目录,http://www.xxx.com/hello/test/, 那么$uri/就是 /hello/test/
3. @locationName表示一个location规则,指向一个location,里面可以配置规则,或者include .htaccess的规则
4. 上面的写法是,先按$uri找文件,找不到,按后面的$uri/找目录,最后按照location去找,找不到返回404

实际访问一个路径,会判断是文件还是目录,文件找$uri, 找不到就location,目录找$uri/,找不到就location,不会机械的依次查找

3. 伪静态配置

例如:
http://www.xxx.com/index.php?name=will&age=20 静态化为 http://www.xxx.com/will/20/index.html
http://www.xxx.com/content/list.php?id=3 静态化为 http://www.xxx.com/content/list/3.html

3.1 nginx配置:

server {
    listen       80;
    server_name  localhost;
    access_log  logs/localhost.access.log  main;
    #开启伪静态日志,方便调试
    rewrite_log on;
    #输出错误日志,错误级别设置为notice
    error_log logs/error-test.log notice;

    root html/test;
    index  index.php index.html;
    location / {
        try_files $uri $uri/ @locStatic;
    }

    //注意使用@符号,不然不成功
    location @locStatic {
        include D:/nginx/html/test/.htaccess;
    }

    location ~ .php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

3.2 .htaccess配置

在htaccess文件中配置rewrite规则

rewrite 语法格式:
rewrite [regex] [replacement] [flag];
url正则表达式 替换真实url 标记(last,break)

具体配置:

rewrite ^/content/list/([0-9]+).html$ /content/list.php?id=$1 last;


参考:http://blog.sina.com.cn/s/blog_bd418dfa0102wser.html

原文地址:https://www.cnblogs.com/mengff/p/12779060.html