Nginx Rewrite语法规则和伪静态规则详解
nginx吧
全部回复
仅看楼主
level 1
打击难题 楼主
nginx里使用伪静态是直接在nginx.conf 中写规则的,并不需要像apache要开启写模块(mod_rewrite)才能进行伪静态。
nginx只需要打开nginx.conf配置文件,在server里面写需要的规则即可。
申请阿里云服务器等产品时,可以使用2000元阿里云代金券,阿里云官网领取网址:https://dashi.aliyun.com/site/yun/youhui
复制代码 代码如下:
server { listen 80; server_name bbs.jb51.net; index index.html index.htm index.php; root /home/www/bbs; error_page 404 /404.htm; #配置404错误页面 location ~ .*.(php|php5)?$ { #fastcgi_pass unix:/tmp/php-cgi.sock; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fcgi.conf; }
下面就是伪静态了location /{ rewrite ^(.*)/equip(d+).html$ $1/index.php?m=content&c=index&a=lists&catid=$2 last; }
然后重启nginx服务器伪静态就生效了,这种维护起来很是不方便我们可以把它写在外部文件如bbs_nginx.conf中
在/home/www/bbs目录下创建bbs_nginx.conf文件并写入以下代码:
复制代码 代码如下:
location /{ rewrite ^(.*)/equip(d+).html$ $1/index.php?m=content&c=index&a=lists&catid=$2 last; }
然后在上面的代码后面加上如下代码:
复制代码 代码如下:
include /home/www/bbs/bbs_nginx.conf;
这样网站根目录中的bbs_nginx.conf伪静态规则,即可实现单独管理。
下面是一个实例:
1. 在使用.htaccess文件的目录下新建一个.htaccess文件,如下面一个Discuz论坛目录:
复制代码 代码如下:
vim /var/www/html/jb51/bbs/.htaccess
2. 在里面输入规则,我这里输入Discuz的伪静态规则(这里仅增加Discuz的伪静态规则):
复制代码 代码如下:
# nginx rewrite rule rewrite ^(.*)/archiver/((fid|tid)-[w-]+.html)$ $1/archiver/index.php?$2 last; rewrite ^(.*)/forum-([0-9]+)-([0-9]+).html$ $1/forumdisplay.php?fid=$2&page=$3 last; rewrite ^(.*)/thread-([0-9]+)-([0-9]+)-([0-9]+).html$ $1/viewthread.php?tid=$2&extra=page%3D$4&page=$3 last; rewrite ^(.*)/profile-(username|uid)-(.+).html$ $1/viewpro.php?$2=$3 last; rewrite ^(.*)/space-(username|uid)-(.+).html$ $1/space.php?$2=$3 last; rewrite ^(.*)/tag-(.+).html$ $1/tag.php?name=$2 last; # end nginx rewrite rule
wq保存退出。
3. 修改nginx配置文件:
4. 在需要添加伪静态的虚拟主机的server{}中引入.htaccess文件:
复制代码 代码如下:
include /var/www/html/jb51/bbs/.htaccess; (备注:把路径改成你.htaccess文件的具体位置)
wq保存退出。
5. 重新加载nginx配置文件:
/etc/init.d/nginx reload
2020年04月27日 11点04分 1
1