2013-08-18 47 views
6

kết quả mong muốn:.htaccess viết lại: tên miền phụ như GET var và đường dẫn như GET var

http://example.com/     -> index.php 
http://www.example.com/    -> index.php 
http://hello.example.com/   -> index.php?subdomain=hello 
http://whatever.example.com/  -> index.php?subdomain=whatever 
http://example.com/world   -> index.php?path=world 
http://example.com/world/test  -> index.php?path=world/test 
http://hello.example.com/world/test -> index.php?subdomain=hello&path=world/test 

Với .htaccess Tôi có ngay bây giờ, tôi có thể đạt được một hoặc tái lập bản đồ khác, nhưng không phải cả hai tại cùng lúc.

RewriteEngine On 

# Parse the subdomain as a variable we can access in PHP, and 
# run the main index.php script 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{HTTP_HOST}  !^www 
RewriteCond %{HTTP_HOST}   ^([^\.]+)\.([^\.]+)\.([^\.]+)$ 
RewriteRule ^.*$ index.php?subdomain=%1 

# Map all requests to the 'path' get variable in index.php 
RewriteBase/
RewriteRule ^index\.php$ - [L] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php?path=$1 [L] 

Tôi đang gặp khó khăn khi kết hợp hai ... bất kỳ con trỏ nào, vui lòng?

EDIT
Các hành vi không mong muốn Tôi đang gặp bây giờ là nếu tôi có một tên miền phụ và đường dẫn sau .com /, chỉ có tên miền phụ sẽ được đi qua, ví dụ:

http://hello.example.com/world-> index.php?subdomain=hello 
+0

http://stackoverflow.com/questions/25582265/mod-rewrite-setting-subdomain-and-directory-to-get-variable – shaunw

+0

có thể tốt hơn nếu bạn kết hợp VirtualHosts để xử lý tên miền phụ và .htaccess để xử lý url viết lại. Hai năm sau, làm thế nào để bạn giải quyết điều này? –

Trả lời

7

Sử dụng các quy tắc đầu tiên để thêm tham số subdomain, mà không thay đổi URI, sau đó sử dụng quy tắc 2 để định tuyến URI để index.php:

RewriteEngine On 

# Parse the subdomain as a variable we can access in PHP, and 
# run the main index.php script 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{HTTP_HOST}  !^www 
RewriteCond %{HTTP_HOST}   ^([^\.]+)\.([^\.]+)\.([^\.]+)$ 
RewriteRule ^(.*)$ /$1?subdomain=%1 

# Map all requests to the 'path' get variable in index.php 
RewriteRule ^index\.php$ - [L] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php?path=$1 [L,QSA] 

Nguyên tắc thứ hai cần để có cờ QSA, nếu không thì chuỗi truy vấn của quy tắc đầu tiên sẽ bị mất.

+0

Ah, 'chuỗi truy vấn chắp thêm', thú vị! Rất thông tin, cảm ơn. –

+0

Xin chào Jon Lin cách viết lại như http://admin.example.com/ -> http://example.com/admin/ – SKG

+0

Đoạn mã trên dường như không hoạt động cho ví dụ cuối cùng của OP (http: // hello.example.com/world/test). Nó sẽ lặp lại đoạn thứ hai (/ test) hai lần trong 'path =' var là '/ world/test/test'. – shaunw