[英]Edit .htaccess with PHP
我有一個.htaccess將域映射到文件夾。
RewriteEngine On
RewriteBase /
# redirect mapped domain
ReWriteCond %{HTTP_HOST} joshblease.uk.to
ReWriteCond %{REQUEST_URI} !gme-index/
ReWriteRule ^(.*)$ gme-index/$1 [L]
有沒有辦法使用PHP編輯/添加額外的域映射到文件?
簡單地說,我想獲取.htaccess文件的內容並使用PHP腳本添加到它們中。
正如上面的一條評論中所建議的那樣,最好在這里使用RewriteMap ,而不是直接嘗試從PHP代碼編輯.htaccess。 以下是如何使用它的示例:
將以下行添加到httpd.conf文件中:
RewriteMap domainMap txt://path/to/domain-dir.txt
像這樣創建一個文本文件/path/to/domain-dir.txt
:
sub1 /subdir1 sub2 /foodir2 foo /bar
在.htaccess文件中添加以下行:
Options +FollowSymLinks -MultiViews RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*)\\.domain\\.com$ [NC] RewriteRule ^$ ${domainMap:%1} [L,R]
實際上,所有這些方法都是將這些重定向到位:
sub1.domain.com/ => sub1.domain.com/subdir1
sub2.domain.com/ => sub2.domain.com/foodir2
foo.domain.com/ => foo.domain.com/bar
優點:有了這個設置,您可以根據需要編輯或重新創建文件/path/to/domain-dir.txt
,而無需打開巨大的安全漏洞,允許php代碼直接編輯.htaccess。
這可能適用於您的情況:
修改.htaccess以查看以下內容:
RewriteEngine On
RewriteBase /
# redirect mapped domain
ReWriteCond %{HTTP_HOST} joshblease.uk.to
ReWriteCond %{REQUEST_URI} !gme-index/
ReWriteRule ^(.*)$ gme-index/$1 [L]
###CUSTOM RULES###
PHP腳本假設$規則保持新生成的規則被修改;
$htaccess = file_get_contents('/path/to/.htaccess');
$htaccess = str_replace('###CUSTOM RULES###', $rules."\n###CUSTOM RULES###", $htaccess);
file_put_contents('/path/to/.htaccess', $htaccess);
上面的例子是理論,並且尚未經過測試,將依賴於.htaccess權限和腳本的權限。
您可以使用以下htaccess將除maindomain.com
之外的任何域maindomain.com
到與域名同名的文件夾。
RewriteCond %{ENV:REDIRECT_STATUS} ^$
ReWriteCond %{HTTP_HOST} !maindomain.com
ReWriteCond %{HTTP_HOST} (.*)
ReWriteRule ^(.*)$ %1/$1 [L]
交替; 將文件夾映射到沒有有限公司的域名。
RewriteCond %{ENV:REDIRECT_STATUS} ^$
ReWriteCond %{HTTP_HOST} !maindomain.com
ReWriteCond %{HTTP_HOST} ^([^\.]*)
ReWriteRule ^(.*)$ %1/$1 [L]
不完全是你想要的,但它可能適合你,並且不需要任何PHP。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.