# rails 設置404頁面 ###### tags: `rails`, `ruby` 環境: > ruby 2.6.7 > > Rails 6.1.3.1 > > Ubuntu 20.04 LTS <font size=4>**為了防止網頁,可能連結出錯;或是手殘輸錯網址跳出錯誤頁面 以下畫面:**</font> ![](https://i.imgur.com/0XjDHyc.jpg) ## :memo: ### Step 1: 移至專案內的application_controller.rb ```ruby= #路徑: /appname/app/controllers/application_controller.rb class ApplicationController < ActionController::Base ++ rescue_from ActiveRecord::RecordNotFound, with: :record_not_found ++ private ++ def record_not_found ++ render file: "#{Rails.root}/public/404.html", ++ status: :not_found, ++ layout: false ++ end end ``` :rocket: ### Step 2: 簡單自訂化404頁面 ```htmlmixed= <!DOCTYPE html> <html> <head> <title>ページが見つかりませんでした (404)</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css"> </head> <body> <div class="content"> <div class="notification is-danger"> <h1 class="title">お探しのページは見つかりません</h1> <p>URL(アドレス)の綴りを誤って入力されているかもしれない。</p> </div> </div> </body> </html> ``` **以下為結果畫面:** ![](https://i.imgur.com/OqBBEzt.jpg)