Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

使用 YOUrls 自架縮網址服務

最近因為 bitly 的 API 更新,收費方式也改變,想說趁這個機會學習新的技能。

架設環境

架設步驟

開設 vhost

$ lnmp vhost add

安裝相依性元件(自行架設伺服器環境必須)

$ sudo apt update
$ sudo apt install -y php php-fpm php-cli php-mysql php-zip php-gd php-mbstring php-curl php-xml php-pear php-bcmath
$ mysql -u root -p //建立資料庫
mysql> CREATE DATABASE yourls;
GRANT ALL PRIVILEGES ON yourls.* TO 'yourls'@'localhost' IDENTIFIED BY "StrongPassword";
FLUSH PRIVILEGES;
QUIT

下載原始碼

$ cd /home/wwwroot/YOURVHOST //網站根目錄
$ git clone https://github.com/YOURLS/YOURLS.git
$ mv YOURLS/* ./ //將檔案移至網站根目錄
$ cd user
$ cp config-sample.php config.php

設定資料庫組態

$ vim config.php

關於資料庫組態的設定可以參考這篇文章。主要是把資料庫的連結方式填寫完整就好。這邊提供組態的一些中文翻譯。

<?php
*
 ** MySQL settings - You can get this info from your web host
 */
/** MySQL 資料庫使用者名稱 */
define( 'YOURLS_DB_USER', 'yourls' );
/** MySQL 資料庫密碼 */
define( 'YOURLS_DB_PASS', 'StrongPassword' );
/** YOURLS 所使用的資料庫名稱 */
define( 'YOURLS_DB_NAME', 'yourls' );
/** MySQL 主機
 ** 如果使用其他連接埠,需要明確指定為 hostname:port,例如:localhost:9999 或 127.0.0.1:666 */
define( 'YOURLS_DB_HOST', 'localhost' );
/** MySQL 資料表前綴 */
define( 'YOURLS_DB_PREFIX', 'yourls_' );
/*
 ** 網站選項
 */
/** YOURLS 安裝網址 -- 只接受小寫字母,末尾不需要加入斜線 /
 ** 如果在此定義 "http://sho.rt" 請不要在瀏覽器使用 "http://www.sho.rt" 存取,反之亦然 */
define( 'YOURLS_SITE', 'http://yourdomain' ); //這邊可以用 https
/** 主機相對 GMT 時區  */
define( 'YOURLS_HOURS_OFFSET', '+8' ); //台灣是 +8
/** 允許存取本網站的使用者帳號與密碼。密碼可以以明文或雜湊加密之形式輸入。
 ** YOURLS 將會自動加密本檔案中的密碼。
 ** 詳情可參閱 http://yourls.org/userpassword */
$yourls_user_passwords = array(
        'eric.chuang' => 'Bw9-$L/3ykq}s#UA',
        // 'username2' => 'password2',
        // 你可以以下列形式新增多位使用者 'login'=>'password'
);

設定伺服器組態(以 nginx 為例)

$ vim /usr/local/nginx/conf/vhost/yourdomain.conf
server {
  listen 80;
  server_name example.com www.example.com;
  root /home/wwwroot/YOURVHOST;
  index index.php index.html index.htm;
  listen [::]:80;
  location / {
    try_files $uri $uri/ /yourls-loader.php$is_args$args;
  }
# 以下這一段由於我使用的堆疊程式碼已經有 pathinfo 的設定,因此可以省略
#  location ~ \.php$ {
#    try_files $uri =404;
#    fastcgi_split_path_info ^(.+\.php)(/.+)$;
#    fastcgi_index index.php;
#    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
#    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
#    include fastcgi_params;
#  }
}
# 修改完畢後儲存
$ nginx -t
$ lnmp nginx restart //或相對應重啟 nginx 之指令
$ cd /home/wwwroot
$ chmod -R www:www YOURVHOST //賦予 Web 存取權

進入安裝介面

輸入 http://yourdomain/admin 進入安裝介面。

點選 Install YOURLS,這個步驟真的就一鍵安裝了

完成後就可以用剛才的帳號密碼進行登入。一旦登入成功後,剛才在 config.php 的密碼就會被雜湊加密了。

試著將這篇文章進行縮網址,因為在截圖當下這篇文章還是非公開的草稿,因此會顯示「找不到頁面」。

參考資料

Eric Chuang
Eric Chuang

正職是廣告行銷人員,因為 Google Tag Manager 的關係開始踏入網站製作的領域,進一步把 WordPress 當成 PHP + HTML + CSS + JavaScript 的學習教材。此外,因為工作的關係,曾經用 Automattic 的 Underscores (_s) 替客戶與公司官網進行全客製化佈景主題開發。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料