3

[Rails] 禁止非 Production 環境下被搜尋引擎建立索引,提升網站 SEO

 2 years ago
source link: https://blog.niclin.tw/2018/08/05/rails-%E7%A6%81%E6%AD%A2%E9%9D%9E-production-%E7%92%B0%E5%A2%83%E4%B8%8B%E8%A2%AB%E6%90%9C%E5%B0%8B%E5%BC%95%E6%93%8E%E5%BB%BA%E7%AB%8B%E7%B4%A2%E5%BC%95%E6%8F%90%E5%8D%87%E7%B6%B2%E7%AB%99-seo/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

除了把關鍵字的 SEO 做好以外,也要注意被「禁止收錄」的部分,有時我們會有其他的環境,例如 staging, 用不同的域名或是 subdomain 下去做等等,在這些情況下,不要讓搜尋引擎收錄網頁其實是有好處的,如果一個網站被收錄了很多對搜尋結果沒有幫助的網頁,反而會讓搜尋引擎認為網站內容空洞,導致網站的權重下降,所以排除這些不重要頁面也是 SEO 中的一個有用的方向。

如何查詢網站是否被收錄

  1. 以 google 來說,可以用 site:yourapp.com 來搜尋,可以查詢不想要被收錄的部分是否已經建立索引了。
  2. 查看 search console 的索引狀態,可以看一下有沒有被過度收錄的情況。

排除收錄的方法

因為不同的搜尋引擎可能會有不同的參考標的,所以盡量就是做到全面。

主要是兩招

  1. <meta> noindex 標籤
  2. robots.txt 檔案

meta noindex

先建立一個 helper

# app/helpers/application_helper.rb
  def render_ban_spider_from_crawling_meta_tag
    tag(:meta, { name: "robots", content: "noindex, nofollow" })
  end

在 view layout 中的

內都加上

<%= render_ban_spider_from_crawling_meta_tag unless Rails.env.production? %>

可以解絕大多數問題,操作也不難,缺點大概就是要單頁設定,如果 layout 很多就會有執行困難,但 Rails 中應該是還好。

robots.txt

把 public 中的 robots.txt 先搬過去 config/ 下 然後製作所有環境的 config/robots.environment.txt

$ mv public/robots.txt config/robots.production.txt
$ cp config/robots.production.txt config/robots.development.txt
def robots                                                                                                                                      
  robots = File.read(Rails.root + "config/robots.#{Rails.env}.txt")
  render text: robots, layout: false, content_type: "text/plain"
end
# routes.rb

get "/robots.txt" => "home#robots"

開發、staging 模式下, Disallow 所有

# robots.development.txt
# (moved from public/robots.txt)
#
# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
#
# To ban all spiders from the entire site uncomment the next two lines:
User-Agent: *
Disallow: /

Production 預設是沒有設定,這裡可以自行設定

# robots.production.txt
# (moved from public/robots.txt)
#
# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
#
# To ban all spiders from the entire site uncomment the next two lines:
# User-Agent: *
# Disallow: /

部屬後過陣子應該就會更新索引了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK