摘自:https://yq.aliyun.com/articles/44682
利用nginx泛域名解析配置二級域名和多域名,實現二級域名子站,用戶個性獨立子域名。
主要針對用戶獨立子域名這種情況,不可能在配置里面將用戶子域名寫完,因此需要通過nginx泛解析方式。
配置方法:
server_name ~^(?<subdomain>.+)\.yourdomain\.com$;
通過匹配subdomain即可。而在下面的可以通過$subdomain這個變量獲取當前子域名稱。
情況一:綁定子域名到統一目錄,作為用戶個性域名
這種情況下,只需要直接匹配就可以了,目錄都是指向同一個地方的(一般)。
配置實例:
server { listen 80; server_name yourdomain.com www.yourdomain.cpm ~^(?<subdomain>.+)\.m\.yourdomain\.com$; index index.php index.html index.htm; set $root_path '/var/www/yanue.net'; root $root_path; try_files $uri $uri/ @rewrite; location @rewrite { rewrite ^/(.*)$ /index.php?_url=/$1; } location ~ \.php { fastcgi_pass 127.0.0.1:9000; } location ~* ^/(css|img|js|flv|swf|download)/(.+)$ { root $root_path; } location ~ /\.ht { deny all; } }
這樣可以實現:
user.m.yourdomain.com
跳轉到用戶自己頁面
當然跳轉邏輯需要自己在程序里面去實現。
情況二:綁定子域名到不同目錄(子站)
網站的目錄結構為
html
├── bbs
└── www
html為nginx的安裝目錄下默認的存放源代碼的路徑。
bbs為論壇程序源代碼路徑
www為主頁程序源代碼路徑
把相應程序放入上面的路徑通過
http://www.youdomain.com 訪問的就是主頁
http://bbs.yourdomain.com 訪問的就是論壇
其它二級域名類推。
配置實例:
server { listen 80; server_name ~^(?<subdomain>.+)\.yourdomain\.com$; root html/$subdomain; index index.html index.htm index.php; fastcgi_intercept_errors on; error_page 404 = /404.html; location / { # This is cool because no php is touched for static content. # include the "?$args" part so non-default permalinks doesn't # break when using query string try_files $uri $uri/ =404; } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # 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; fastcgi_param domain $subdomain; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } }