月初的时候折腾了一下服务器的迁移,在备份网站的时候发现这个备份文件比较大,在下载或者上传的时候也挺费时间,一开始没想这么多,想把网站迁移完了再说。
知道最近几天使用SEMrush综合SEO工具检测了一下,发现里面有些问题,提示使用的一些css, js之类的可能影响网站速度,可以发现使用了一些是插件下面的东西,如果不影响速度,也可以不用管就行了。

wordpress plugins
但是总是看着有问题得想着解决,于是又折腾了一下,当然,下面的所有布局最好是在建站前期全部部署好,会省很多事情,不用去做301跳转之类的,也不用担心以后文章被收入又降权的问题。
能不使用插件的尽量不要使用插件,免得消耗资源。
下面来看一下几种常见的可以使用代码替换插件的方法,减少对服务器的消耗。
第一,安装SSL证书后实现HTTPS进行全站跳转
简单的方法,当然可以使用插件来实现,而且设置也是很简单,不用折腾代码,这是最便捷的实现方法,插件可以使用really simple ssl,有需要的可以在你博客后台插件-->安装新插件,搜索really simple ssl即可,安装插件设置也是非常简单如下图:
如何使用代码实现跳转呢?下面来看一下用什么代码实现,加到什么位置,当然使用宝塔面板可以在安装SSL证书的右上角直接强制HTTPS即可,下面我们来看一下代码:
- server {
- listen 80;
- server_name xxxx.com ; #将xxxx修改为您证书绑定的域名,例如:www.xxxx.com。
- rewrite ^(.*)$ https://$host$1 permanent; #将所有http请求通过rewrite重定向到https。
- location / {
- index index.html index.htm;
- }
- }
将代码加到nginx.conf文件中,当然,如果你是使用Apache的话设置如下;
修改httpd.conf文件,设置HTTP请求自动跳转HTTPS。
在httpd.conf文件中的<VirtualHost *:80> </VirtualHost>中间,添加以下重定向代码。
- RewriteEngine on
- RewriteCond %{SERVER_PORT} !^443$
- RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [L,R]
参考文档:在Apache服务器上安装SSL证书
第二,伪静态设置固定链接路径改变后如何实现旧链接301跳转到新链接,使老链接权重传递到新链接。
这个是在没有经验的新手博主常见的问题,比如我自己当初的时候就是吃过这样的亏,直接买了服务器安装上就开始发内容,没有做前期的设置,当改变了伪静态的固定链接的结构后,访问老链接就变成空的。
使用插件WP Permalinks Migration也是非常简单实现,设置也是非常简单,将旧伪静态固定链接结构填入输入框中即可,可以到插件提供页面查看详情,如下图所示:
使用代码如何实现伪静态固定旧链接跳转到新链接呢?
将以下代码加入到主题文件夹下面的functions.php文件中,将代码加到<?php .....?>之间,一般直接加到最后面就可以了。如果已经被搜索引擎收录了好多,以前的地址都无法访问了,所以要做好301重定向,跳转到新的固定链接所生成的地址中去,要不然都是404就悲剧了。下面代码可以解决
- $rewrite_config = array();
- $rewrite_config['highpriority'] = true ;
- $rewrite_config['rewrite'] = array();
- $rewrite_config['oldstructure'] = "/%category%/%post_id%.html";
- function wpdaxue_pm_the_posts($post) {
- global $wp;
- global $wp_rewrite;
- global $rewrite_config;
- $rewrite_config['rewrite'] = $wp_rewrite->generate_rewrite_rule($rewrite_config['oldstructure'], false, true, true, true);
- if ($post != NULL && is_single() && $rewrite_config['oldstructure'] != $wp_rewrite->permalink_structure) {
- if (array_key_exists($wp->matched_rule, $rewrite_config['rewrite'])) {
- // ok, we need to generate a 301 Permanent redirect here.
- header("HTTP/1.1 301 Moved Permanently", TRUE, 301);
- header('Status: 301 Moved Permanently');
- $permalink = get_permalink($post[0]->ID);
- if (is_feed()) {
- $permalink = trailingslashit($permalink) . 'feed/';
- }
- header("Location: ". $permalink);
- exit();
- }
- }
- return $post;
- }
- function wpdaxue_pm_post_rewrite_rules($rules) {
- global $wp_rewrite;
- global $rewrite_config;
- $oldstruct = $rewrite_config['oldstructure'];
- if ($oldstruct != NULL && $oldstruct != $wp_rewrite->permalink_structure) {
- $rewrite_config['rewrite'] = $wp_rewrite->generate_rewrite_rule($oldstruct, false, true, true, true);
- if ($rewrite_config ['highpriority'] == true) {
- return array_merge($rewrite_config['rewrite'], $rules);
- } else {
- return array_merge($rules, $rewrite_config['rewrite']);
- }
- }
- return $rules;
- }
- add_filter('the_posts', 'wpdaxue_pm_the_posts', 20);
- add_filter('post_rewrite_rules', 'wpdaxue_pm_post_rewrite_rules');
将我的$rewrite_config['oldstructure'] = “/%category%/%post_id%.html”中的/%category%/%post_id%.html修改成你自己的旧的固定链接格式,然后将这段代码加入到主题的functions.php中,然后设置成新的固定链接格式就可以了.
当然还有其他的方法,比如,服务器是ngnix环境的话,加这段代码到ngnix.conf里面。
- rewrite ^/(.+)/(d+).html$ /$2.html permanent
301重定向代码一定要放在wordpress伪静态规则之前,否则不生效!给一下完整的句子顺序如下:
- server
- {
- listen 80;
- server_name kjgou.net;
- index index.html index.htm index.php default.html default.htm default.php;
- root /home/nuodou;
- rewrite ^/(.+)/(d+).html$ /$2.html permanent;#修改固定链接后,做301重定向
- #wordpress伪静态
- if (!-e $request_filename){
- rewrite ^(.+)$ /index.php?q=$1 last;}
- include none.conf;
- ……此处略去N个字符……
- }
解释一下上面的意思,我原来的固定链接结构是/%category%/%post_id%.html,新的固定结构是/%post_id%.html,其中,%post_id%肯定是数字,正则表达式中(d+)对应任意数字,所以以前的网址可以写成/(d+),而%category%是分类,肯定是字符,不管是汉字还是字母,正则表达式中(.+) 对应的是任意字符(包括汉字、英文字母等),所以旧的网址可以写成/(.+)/(d+).html,因为%post_id%是旧网址的第二个变量,所以整句就是rewrite ^/(.+)/(d+).html$ /$2.html permanent,permanent是实现301跳转的意思。
- ^ –> 匹配字符串的开始
- $ –> 匹配字符串的结束
(d+)后面的$是结束前面格式,执行后面格式。
下面这种方法需要根据自己的情况进行修改变量,需要花一定的时间进行理解,不一定能把自己的格式写对,所以还以用第一种方便,直接更换一下以前的链接就可以了。
第三,如何实现外链实现自动nofollow属性,及新窗口打开?
做过网站的人都知道,如果外链不加nofollow属性的话,会将权重传递到外链链接,为了减少权重传递流失,很多懂的人都会对外链加nofollow属性,从而搜索引擎蜘蛛在爬行的时候不再对外链链接抓取,保证本站的权重。
我们可以安装插件来实现,在进行外链设置的时候将nofollow选项打勾,这样的话可以实现外链的nofollow属性,但是每个链接得手动设置,有点花时间麻烦。
但是我们也可以使用代码来实现外链nofollow属性及新窗口打开链接,从而工作一劳永逸,不用每次每个链接都要手动加上去,将如下代码加到functions.php文件中.
- // 文章页面外链自动添加nofollow属性和新窗口打开
- add_filter( 'the_content', 'cn_nf_url_parse');
- function cn_nf_url_parse( $content ) {
- $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
- if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
- if( !empty($matches) ) {
- $srcUrl = get_option('siteurl');
- for ($i=0; $i < count($matches); $i++)
- {
- $tag = $matches[$i][0];
- $tag2 = $matches[$i][0];
- $url = $matches[$i][0];
- $noFollow = '';
- $pattern = '/target\s*=\s*"\s*_blank\s*"/';
- preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
- if( count($match) < 1 )
- $noFollow .= ' target="_blank" ';
- $pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
- preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
- if( count($match) < 1 )
- $noFollow .= ' rel="nofollow" ';
- $pos = strpos($url,$srcUrl);
- if ($pos === false) {
- $tag = rtrim ($tag,'>');
- $tag .= $noFollow.'>';
- $content = str_replace($tag2,$tag,$content);
- }
- }
- }
- }
- $content = str_replace(']]>', ']]>', $content);
- return $content;
- }
或者:
- add_filter('the_content', 'auto_nofollow'); //nofollow文章中的站外链接
- add_filter('comment_text', 'auto_nofollow'); //nofollow评论中的站外链接
- function auto_nofollow($content) {
- //return stripslashes(wp_rel_nofollow($content));
- return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
- }
- function auto_nofollow_callback($matches) {
- $link = $matches[0];
- $site_link = get_bloginfo('url');
- if (strpos($link, 'rel') === false) {
- $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
- } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
- $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
- }
- return $link;
- }
这里有两种代码,我用的是前一种,你也可以尝试使用后面那种代码,先测试一下是否可以,如果可以的话,使用哪种都可以,只要能实现就可以了,很多博主跟我一样不是专业IT人员,不知道代码里面具体的意思。
第四,如何将文章链接默认的category去掉?
如果我们不做任何设置的话,我们发布的每一篇文章都会带有category,即:https://kjgou.net/category/123.html,从而增加了链接的深度,从而对搜索引擎的蜘蛛爬行增加了难度,对SEO就不太友好。
为了去除这个category,我也是找遍各种方法,最简单粗暴的就是安装插件,可以使用插件No Category Base (WPML),轻松将category去掉。
下面我们来看一下如何使用代码,将以下代码加到functions.php中,从而实现去除category的目的。
- //去除分类标志代码
- add_action( 'load-themes.php', 'no_category_base_refresh_rules');
- add_action('created_category', 'no_category_base_refresh_rules');
- add_action('edited_category', 'no_category_base_refresh_rules');
- add_action('delete_category', 'no_category_base_refresh_rules');
- function no_category_base_refresh_rules() {
- global $wp_rewrite;
- $wp_rewrite -> flush_rules();
- }
- // register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
- // function no_category_base_deactivate() {
- // remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
- // // We don't want to insert our custom rules again
- // no_category_base_refresh_rules();
- // }
- // Remove category base
- add_action('init', 'no_category_base_permastruct');
- function no_category_base_permastruct() {
- global $wp_rewrite, $wp_version;
- if (version_compare($wp_version, '3.4', '<')) {
- // For pre-3.4 support
- $wp_rewrite -> extra_permastructs['category'][0] = '%category%';
- } else {
- $wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
- }
- }
- // Add our custom category rewrite rules
- add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
- function no_category_base_rewrite_rules($category_rewrite) {
- //var_dump($category_rewrite); // For Debugging
- $category_rewrite = array();
- $categories = get_categories(array('hide_empty' => false));
- foreach ($categories as $category) {
- $category_nicename = $category -> slug;
- if ($category -> parent == $category -> cat_ID)// recursive recursion
- $category -> parent = 0;
- elseif ($category -> parent != 0)
- $category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
- $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
- $category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
- $category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
- }
- // Redirect support from Old Category Base
- global $wp_rewrite;
- $old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
- $old_category_base = trim($old_category_base, '/');
- $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
- //var_dump($category_rewrite); // For Debugging
- return $category_rewrite;
- }
- // Add 'category_redirect' query variable
- add_filter('query_vars', 'no_category_base_query_vars');
- function no_category_base_query_vars($public_query_vars) {
- $public_query_vars[] = 'category_redirect';
- return $public_query_vars;
- }
- // Redirect if 'category_redirect' is set
- add_filter('request', 'no_category_base_request');
- function no_category_base_request($query_vars) {
- //print_r($query_vars); // For Debugging
- if (isset($query_vars['category_redirect'])) {
- $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
- status_header(301);
- header("Location: $catlink");
- exit();
- }
- return $query_vars;
- }
提醒: 使用代码之后,网站可能会出现 404 页面,也即%post_id%.html(本站的固定链接)的伪静态失效了,解决办法很简单,登录后台>>设置>>固定链接设置页面,把固定链接格式改成别的,然后再改回自己常用的格式,保存一下就可以解决这个 bug,不行就多改几次。如果还不行就把所有缓存清除后再尝试。
目前我所遇到的就这几个可以使用代码代替插件来实现的方法,当然,如果你的IT技术人员的话,基本大部分的都是可以代码来操作了,从而减少不必要资源消耗,影响网站速度。
以上代码均来自网络,大家使用的时候先测试一下,稳妥了再替换插件。
如果你有什么好的其他方便用代码实现的功能,可以留言交流,共同进步。
还有最好,使用一些检测工具检测一下网站的问题,然后做优化,能优化的地方尽量优化好,我使用的是SEMrush工具,现在注册使用有45美金的折扣,需要的话可以点击注册SEMrush使用,当然你可以使用能检测的工具就可以了。
发表于2021-08-13 at 13:50 0楼
网站很棒!~~~~