下面是一个server配置实例,支持/和/wordpress/俩个独立的网站。
server { listen 80 default_server; server_name liungkejin.wang; # Default root and index. root /var/www/monbook; index index.php; location / { root /var/www/monbook; index index.php; if (!-e $request_filename) { rewrite ^/(.*) /index.php last; } } location /wordpress/ { root /var/www; index index.php; # rewrite ^/wordpress/(.*)$ /wordpress/$1 break; 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; } } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # 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; } }
主要有两点需要关注:
- location代表匹配规则:匹配分两种:前缀式、正则式。按最长匹配原则,先匹配前缀式。然后,按定义的顺序匹配正则式。location可以嵌套。
- rewrite规则匹配到之后,会重新location匹配,不会超过10次。break flag,则表示不再location匹配;last flag,不再实行当前的序列。
也很好理解:首先,根据请求的URI匹配一个location,当location内定义的rewrite改变了uri,则需要重新匹配。