如何快速查找URL對應重導後的URL-使用Python

有時有些URL會因為分析, 或是廣告等原因, 需要進行重導(redirect), 然而在程式實作上, 若需要找到這個重導的結果URL, 要如何進行呢? 可以使用 requests library 的訪問連結後來取得, 程式如下:

response = requests.get('https://youtu.be/dQw4w9WgXcQ') 
print(response.url) # https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be

利用 requests.get 的結果, 再將 response 的 url 取出即可.

參考資料:

https://stackoverflow.com/questions/36070821/how-to-get-redirect-url-using-python-requests

分類
FreeBSD/Linux

Apache使用.htaccess重導新網域

有時因為網域修改, 需要做網域級的重導, 建議使用 301 配合 .htaccess 的設定來進行, 可以使用以下語法:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com$
RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]

其中的 R=301 是使用了 301重導, 而新舊域名可以參考上面語法, 並且使用了 RewriteRule 將任意內容重導至新網域時, 維持相同的網址.

參考資料: https://wpscholar.com/blog/redirect-old-domain-to-new-domain-via-htaccess/

php上實作301 Redirect指示方式

在 php 中若需要重導客戶端, 可以使用 302 重導:

header("Location: http://newlocation");

在不指定 response status 時, 上述內容會使用 302 重導.

若需要使用 301 重導, 可以使用如下程式:

1. 先宣告重導指示, 再進行重導:

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://newlocation");

2. 直接使用 header 中的 response status 參數:

header("Location: http://newlocation", TRUE, 301);

以上兩種方式皆可以重導客戶端至指定目標, 並且以 301 Moved Permanently 方式指示.

繼續閱讀:
https://blog.longwin.com.tw/2015/09/php-301-302-redirect-header-2015/
https://stackoverflow.com/questions/7324645/php-header-redirect-301-what-are-the-implications
https://www.php.net/manual/en/function.header.php

Exit mobile version