WordPress: Difference between revisions

From NixOS Wiki
imported>Onny
Add notes about Wordpress version upgrades
imported>Onny
Update instructions on manually package Wordpress plugins
Line 34: Line 34:
     src = pkgs.fetchurl {
     src = pkgs.fetchurl {
       url = "https://de.wordpress.org/wordpress-${pkgs.wordpress.version}-de_DE.tar.gz";
       url = "https://de.wordpress.org/wordpress-${pkgs.wordpress.version}-de_DE.tar.gz";
       sha256 = "sha256-dlas0rXTSV4JAl8f/UyMbig57yURRYRhTMtJwF9g8h0=";
       hash = "sha256-dlas0rXTSV4JAl8f/UyMbig57yURRYRhTMtJwF9g8h0=";
     };
     };
     installPhase = "mkdir -p $out; cp -r ./wp-content/languages/* $out/";
     installPhase = "mkdir -p $out; cp -r ./wp-content/languages/* $out/";
Line 66: Line 66:
let
let


wordpress-theme-responsive = pkgs.stdenv.mkDerivation {
wordpress-theme-responsive = pkgs.stdenv.mkDerivation rec {
   name = "responsive";
   name = "responsive";
   src = pkgs.fetchurl {
  version = "1.9.7.6";
     url = http://wordpress.org/themes/download/responsive.1.9.7.6.zip;
   src = pkgs.fetchzip {
     sha256 = "06i26xlc5kdnx903b1gfvnysx49fb4kh4pixn89qii3a30fgd8r8";
     url = "http://wordpress.org/themes/download/responsive.${version}.zip";
     hash = "sha256-nITPOBK/ORCGw/l087nsVVtr7VW80BeVthDqJr9M4R0=";
   };
   };
  buildInputs = [ pkgs.unzip ];
   installPhase = "mkdir -p $out; cp -R * $out/";
   installPhase = "mkdir -p $out; cp -R * $out/";
};
};

Revision as of 12:15, 14 January 2023

Wordpress is a self-hosted content management web application, especially designed for blogging but also a good way to start creating your own website. It can be customized with themes and a built-in site editor and further extended with plugins.

Installation

A simple local setup of Wordpress can be enabled with the following setup

services.wordpress.sites."localhost" = {};

Visit http://localhost to setup your new Wordpress instance. By default, a Mysql server is configured automatically so you won't have to setup the database backend.

Configuration

Language

The default language of the Wordpress module will be English. It is possible to enable additional language support for languages which are already packaged. Using extraConfig you can configure the default language. In this example, we're going to enable the German language.

services.wordpress.sites."localhost" = {
  languages = [ pkgs.wordpressPackages.languages.de_DE ];
  extraConfig = ''
    define ('WPLANG', 'de_DE');
  '';
};

Alternatively you can package your own language files following this example:

{ pkgs, ... }: let

  wordpress-language-de = pkgs.stdenv.mkDerivation {
    name = "wordpress-${pkgs.wordpress.version}-language-de";
    src = pkgs.fetchurl {
      url = "https://de.wordpress.org/wordpress-${pkgs.wordpress.version}-de_DE.tar.gz";
      hash = "sha256-dlas0rXTSV4JAl8f/UyMbig57yURRYRhTMtJwF9g8h0=";
    };
    installPhase = "mkdir -p $out; cp -r ./wp-content/languages/* $out/";
  };

in {

  services.wordpress.sites."localhost".languages = [ wordpress-language-de ];

}

Consult the translation portal of Wordpress for the specific country and language codes available. This example is using the code de_DE (Germany/German) in the source URL and also the extraConfig part.

Themes and plugins

Themes and plugins which are already packaged can be integrated like this:

services.wordpress.sites."localhost" = {
  themes = [ pkgs.wordpressPackages.themes.twentytwentytwo ];
  plugins = with pkgs.wordpressPackages.plugins; [
    antispam-bee
    opengraph
  ];
};

Manually package a Wordpress theme or plugin can be accomplished like this:

let

wordpress-theme-responsive = pkgs.stdenv.mkDerivation rec {
  name = "responsive";
  version = "1.9.7.6";
  src = pkgs.fetchzip {
    url = "http://wordpress.org/themes/download/responsive.${version}.zip";
    hash = "sha256-nITPOBK/ORCGw/l087nsVVtr7VW80BeVthDqJr9M4R0=";
  };
  installPhase = "mkdir -p $out; cp -R * $out/";
};

in {

  services.wordpress.sites."localhost" = {
    themes = [ wordpress-theme-responsive ];
  };

}

You can package any available Wordpress extension, for example from the official theme or plugin repository. Be sure to replace the name, url and sha256 part according to your desired extension.

If you want to automatically enable and activate the responsive theme, add this extraConfig line

extraConfig = ''
  define ('WP_DEFAULT_THEME', 'responsive');
'';

In case you want to automatically enable and activate the plugin, in this example akismet, you can add following to extraConfig

extraConfig = ''
  if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');
  require_once(ABSPATH . 'wp-settings.php');
  require_once ABSPATH . 'wp-admin/includes/plugin.php';
  activate_plugin( 'akismet/akismet.php' );
'';

Mail delivery

Mail clients like Msmtp can be used to configure mail delivery for Wordpress. This can be useful for sending registration mails or notifications for new comments etc.

By default Wordpress will use the sender mail wordpress@example.org where example.org is the primary domain name configured for the Wordpress instance. By installing and using the plugin static-mail-sender-configurator it is possible to declaratively configure and change the sender address, for example to noreply@example.org.

services.wordpress.sites."example.org" = {
  plugins = [ pkgs.wordpressPackages.plugins.static-mail-sender-configurator ];
  extraConfig = ''
      // Enable the plugin 
      if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');
      require_once(ABSPATH . 'wp-settings.php');
      require_once ABSPATH . 'wp-admin/includes/plugin.php';
      activate_plugin( 'wordpress-plugin-static-mail-sender-configurator-${pkgs.wordpressPackages.plugins.static-mail-sender-configurator.version}/static-mail-sender-configurator.php' );

    // Change sender mail address
    define ('WP_MAIL_FROM', 'noreply@localhost');
  '';
};

Maintenance

Upgrading

Wordpress automatically performs an database and software upgrade as soon as a new package version is installed. Major version upgrades of the pkgs.wordpress package are performed between every new NixOS release. In case you wish to switch to a newer major Wordpress version while staying on your latest NixOS version, you can choose between Wordpress package versions available in the repository.

For example switch to Wordpress 6.1 while the default Wordpress package version for NixOS 22.11 is 6.0

services.wordpress.sites."example.org" = {
  package = pkgs.wordpress6_1;
};

Tips and tricks

Force https-URLs behind reverse proxy

In case you're running Wordpress behind a reverse proxy which offers a SSL/https connection to the outside, you can force Wordpress to use the https protocol

services.wordpress.sites."localhost".extraConfig = ''
  // Needed to run behind reverse proxy
  define('FORCE_SSL_ADMIN', true);
  $_SERVER['HTTPS']='on';
'';

Search engine optimization (SEO)

Meta information

The Wordpress plugin Yoast SEO helps you to configure meta information of your Wordpress page. You can install it like this

services.wordpress.sites."example.org" = {
  plugins = [ pkgs.wordpressPackages.plugins.wordpress-seo ];
};

After enabling the plugin in the Wordpress admin interface, finish the first-time installation wizard of Yoast SEO. In most cases the free features offered by the plugin should be sufficient, so you won't have to register or enable any premium extensions. Other integrations which are not needed can be disabled in Yoast SEO -> Integrations.

It's worth tweaking settings in Yoast SEO -> Search Appearance. Especially configuring a social image and organization logo including name and description is useful if your page gets shared and indexed.

SEO optimization can be performed page wise. In the page editor you'll find SEO analysis and tips on the right pane.

Picture compression

Your website gets better ranking for search engines if it is optimized to load fast. The Wordpress plugin webp-express compresses your existing and future images automatically into a modern efficient image format and reduces their file size.

Following example installs the plugin and adds an additional writeable directory to the Wordpress package, otherwise the plugin will fail due to permission issues. This hack only works for one specific instance, in this example for example.org. Replace the site name on all occurrences.

services.wordpress.sites."example.org" = {
  plugins = [ pkgs.wordpressPackages.plugins.webp-express ];
};

nixpkgs.overlays = [
  (self: super: {
    wordpress = super.wordpress.overrideAttrs (oldAttrs: rec {
      installPhase = oldAttrs.installPhase + ''
        ln -s /var/lib/wordpress/example.org/webp-express $out/share/wordpress/wp-content/webp-express
      '';
    });
  })
];

systemd.tmpfiles.rules = [
  "d '/var/lib/wordpress/example.org/webp-express' 0750 wordpress wwwrun - -"
];

In the Wordpress administrator interface go to Settings -> WebP Express. One possible configuration which is suitable for the NixOS module could be

  • Scope: Uploads only (we cannot convert theme files)
  • Destination folder: Mingled (save webp converted images in the same place as original files)
  • File extension: Set to ".webp"
  • Destination structure: Image roots
  • Disable all .htaccess rules (doesn't apply for any web server)
  • Convert on upload: yes (future uploads will be converted to webp file format)
  • Alter HTML: Replace image URLs (we'll only reference compressed webp images on the page)
  • Reference webps that haven't been converted yet: Yes
  • How to replace: The complete page

Further click on Bulk convert to convert all existing images.

Lazy load images

Using the Wordpress plugin Jetpack, it is possible to enable lazy loading of images. That means, images only visible in the current view of the web browser are loaded. This will speed up initial page load.

services.wordpress.sites."example.org" = {
  plugins = [ pkgs.wordpressPackages.plugins.jetpack ];
};

After enabling the plugin, in the Wordpress admin interface go to Jetpack -> Settings -> Performance and ensure that lazy loading of Images is enabled. Note that Jetpack comes with a lot of optional modules which should be disabled if not used. On the same page go to Debug in the bottom menu and click on the last link offering the list of all modules. Disable all modules you don't need instead of Lazy Images.

Webserver text compression

Compressing text served by the web server enhances page loading times. This example enables text compression on the webserver Nginx. Please refer upstream documentation in case you're going to use a different web server for your Wordpress setup.

services.nginx.extraConfig = ''
  gzip on;
  gzip_vary on;
  gzip_comp_level 4;
  gzip_min_length 256;
  gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
  gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;
'';

Minify and merge Javascript and CSS

Page load can further optimized by minify and merge Javascript and CSS files. The plugin merge-minify-refresh can be used to achieve this. The following example installs the plugin and creates an additional directory required for the plugin to work. This hack is specified for one specific instance for the domain example.org (replace all occurrences with your preferred domain name). Don't forget to enable the plugin in the Wordpress admin interface.

services.wordpress.sites."example.org" = {
  plugins = [ pkgs.wordpressPackages.plugins.merge-minify-refresh ];
};

nixpkgs.overlays = [
  (self: super: {
    wordpress = super.wordpress.overrideAttrs (oldAttrs: rec {
      installPhase = oldAttrs.installPhase + ''
        ln -s /var/lib/wordpress/example.org/mmr $out/share/wordpress/wp-content/mmr
      '';
    });
  })
];

systemd.tmpfiles.rules = [
  "d '/var/lib/wordpress/example.org/mmr' 0750 wordpress wwwrun - -"
];

Useful online tools

There are some resources which might be useful to check the SEO score of your page

Troubleshooting

Enable logging

To enable logging add the following lines to extraConfig

services.wordpress.sites."localhost".extraConfig = ''
  define( 'WP_DEBUG', true );
  define( 'WP_DEBUG_LOG', true );
  ini_set( 'error_log', '/var/lib/wordpress/localhost/debug.log' );
'';

Since the default location to the folder wp-content is not writable, we redirect the log file path to /var/lib/wordpress/localhost/debug.log. All error messages will be stored there. Change the folder name localhost to the name of your site.

In case you want to print error messages directly in your browser, append following line

services.wordpress.sites."localhost".extraConfig = ''
  @ini_set( 'display_errors', 1 );
'';

Please note that this exposes sensible information about your server setup therefore this option should not be enabled in production.