如何使用 mod_rewrite 刪除 URL 的 2 個單獨部分?

如何使用 mod_rewrite 刪除 URL 的 2 個單獨部分?

我有這個不幸的網址:

dom.tld/library/Photography/index.php?cmd=image&sfpg=2021/*IMG_3468.jpg
dom.tld/library/Photography/index.php?sfpg=2021/*

這應該看起來像這樣

dom.tld/library/Photography/2021/IMG_3468.jpg
dom.tld/library/Photography/2021/

本質上,我想刪除檔案名稱之前的index.php?cmd=image&sfpg=星號。*

資料夾結構如下圖所示:

root /var/www/domain.tld/main/library/Photography -> tree -a
.
|-- .htaccess
|-- index.php
|-- _GalData
|   |-- info
|   |   |-- 2018
|   |   |   |-- April
|   |   |   |   |-- _sfpg_dir
|   |   |   |   `-- image.png
|   |   |   |-- _sfpg_dir
|   |   |   `-- image.png
|   |   |-- 2019
|   |   |   |-- _sfpg_dir
|   |   |   `-- image.png
|   |   `-- _sfpg_dir
|   `-- thumb
|       |-- 2018
|       |   |-- April
|       |   |   `-- image.jpg
|       |   `-- image.jpg
|       `-- 2019
|           `-- image.jpg
`-- synced
    |-- 2018
    |   |-- April
    |   |   `-- image.jpg
    |   `-- image.jpg
    `-- 2019
        `-- image.jpg

真實影像儲存在index.php中synced/並由_GalData/index.php生成,主要網站位於/var/www/domain.tld/main/index.html

答案1

我不能 100% 確定這是最好的方法,但考慮到以下資料夾結構

user@instance-apache:/var/www/html$ tree -a
.
├── .htaccess
├── index.html
└── library
    └── photography
        └── folder
            └── image.jpg

以及 .htaccess 檔案的內容 [更新]

RewriteEngine on
RewriteCond %{QUERY_STRING} .*\=(.*)\*(.*)
RewriteRule (.*/)index.php /$1%1%2 [QSD]

阿帕契應該使

http://127.0.0.1/library/photography/index.php?cmd=image&sfpg=folder/*image.jpg

進入

http://127.0.0.1/library/photography/folder/image.jpg

答案2

.htaccess位於子目錄的檔案中,/library/photography/.htaccess您可以使用 mod_rewrite 執行類似以下操作,以在內部將請求重寫為所需的 URL。

RewriteEngine On

RewriteCond %{QUERY_STRING} (^|&)cmd=image(&|$)
RewriteCond %{QUERY_STRING} (?:^|&)sfpg=([^&*]+)\*([^&]+)(&|$)
RewriteRule ^index\.php$ %1%2 [QSD,L]

首先狀態(RewriteCond指令) 只是確認cmd=imageURL 參數出現在查詢字串中的任何位置。

第二狀態sfpg捕捉URL 參數值中字元周圍的部分*(使用時需要反斜線轉義)外部正規表示式字元類別的名稱,以否定其特殊意義)。然後,它們分別在%1和反向引用中可用%2,並在代換字串(RewriteRule指令的第二個參數)是建構一個相對的檔案路徑(即相對於/library/photography/包含該.htaccess檔案的子目錄)。

URL 參數可以以任意順序出現。例如。?sfpg=folder/*image.jpg&cmd=image也會匹配成功。並且可能還有其他 URL 參數,這些參數將被丟棄。

(查詢字串丟棄)標誌QSD從重寫的請求中刪除原始查詢字串(這對於內部重寫來說並不真正重要)。


在旁邊:

RewriteRule /index.php /

這作為內部重寫實際上沒有意義,因為 和 都/index.php應該/返回相同的資源。 (這通常是作為外部重定向來實現,以解決與重複內容相關的任何 SEO 問題。)


更新:

然而,我認為我在一般方法中發現了一個問題。實際文件並不位於連結所暗示的位置。請查看我更新的問題。

如果我正確理解您的更新,您希望提供的“真實文件”存儲在synced子目錄中,並且sfpgURL 參數引用該子目錄中的文件路徑(減去*)? (所有內容都在/library/Photography子目錄中,包括.htaccess文件。或至少是.htaccess我們正在處理的文件。)

在這種情況下,您似乎只需要RewriteRule透過添加前綴來修改指令代換字串與synced/.例如:

:
RewriteRule ^index\.php$ synced/%1%2 [QSD,L]

(其他一切與上面的規則保持不變,在我的答案的頂部。)

相關內容