問題描述
我正在嘗試我以為會是一個非常簡單的遮蔽我的網址,但似乎無法讓它工作的東西。我想能夠連結到我的 img 標籤中的影像,而不必輸入完整的 URL 。
即
Current url: http://server.com/wp-content/themes/standard/images/img.jpg
or
<img src = "http://server.com/wp-content/themes/standard/images/img.jpg" />
但是在我的網頁上,我想做的只是
<img src="http://server.com/images/img.jpg" />
但是我的本地主機似乎沒有工作。我在 Windows 7 機器上執行 Apache 伺服器。我試圖使用.htaccess 來做我上面提到的。這是我的網站根目錄下的.htaccess 檔案。
更新:我嘗試了下面的 ZweiBlumen 建議,但似乎沒有工作。然後我嘗試了 Geerts 建議,並將 re-write 方法新增到我的 admin 資料夾的 misc.php 中。然後我去了我的永久連結頁面,點選儲存。這樣做的結果意味著我的.htaccess 資料夾被重寫,並且其生成的輸出在下面。
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteRule ^css/(.*) /wp-content/themes/standard/css/$1 [QSA,L]
RewriteRule ^js/(.*) /wp-content/themes/standard/js/$1 [QSA,L]
RewriteRule ^images/(.*) /wp-content/themes/standard/images/$1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
但是,我仍然無法導航到我的影像資料夾,如:
http://localhost/images/myimage.jpg 。
我所得到的是一個沒有找到的頁面。約書亞的建議工作完美,但我希望結合掩蓋圖片的 URL 使用。
還有什麼我可能做錯了,還是應該檢查?
更新:
對於讀這個的人來說,我只是再試一次,它使用了 Geerts 和 Joshuas 方法的組合。我的 Firefox 瀏覽器似乎已經快取了頁面,導致我認為它不是。
我把它放在.htaccess 檔案中的原因是,每次我去永久連結的管理員頁面都會覆蓋這個檔案,所以我不會意外地覆蓋這個檔案。我想我可以把它關掉,但不知道該怎麼做。所有這三個答案在一定程度上有所幫助。
最佳解決方案
檢視 Roots WordPress Theme 。他們似乎完全按照你想要的 URL 來完成。
以下是他們的 roots-htaccess.php 檔案的片段:
add_action( 'generate_rewrite_rules', 'roots_add_rewrites' );
function roots_add_rewrites($content) {
$theme_name = next( explode( '/themes/', get_stylesheet_directory() ) );
global $wp_rewrite;
$roots_new_non_wp_rules = array(
'css/(.*)' => 'wp-content/themes/' . $theme_name . '/css/$1',
'js/(.*)' => 'wp-content/themes/' . $theme_name . '/js/$1',
'img/(.*)' => 'wp-content/themes/' . $theme_name . '/img/$1',
);
$wp_rewrite->non_wp_rules += $roots_new_non_wp_rules;
}
注意:如果您可以直接在.htaccess 檔案中將其關閉,就像 ZweiBlumen 的答案一樣,您應該選擇該解決方案,因為它可能更加最佳化。
次佳解決方案
如果問題只是與影像,但不是 css 或 javascript,我認為你的 RewriteRule 有一個錯字。 “$” 後我覺得你錯過了一個”1″:
RewriteRule ^images/(.*)$ wp-content/themes/standard/images/$1 [L]
此外,您可能想嘗試將這些額外的語句放在初始規則之下,即下面這行:
RewriteRule ^index.php$ - [L]
不確定。
第三種解決方案
為什麼不以下列方式建立一個短碼。
function img_folder_shortcode( ) {
return get_stylesheet_directory_uri() . '/images';
}
add_shortcode( 'img_folder', 'img_folder_shortcode' );
然後在內容區域的任何位置使用以下短程式碼。
[img_folder]/img.jpg
<img src="[img_folder]/img.jpg" alt="img" />
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。