Direct link preview of shared image yeilds 404 from webserver

Hello,

For some reason when I try to publicly share an image for a forum or whatever, the direct link to the preview will not go to the image. By which I mean:

https://cloud.mynextcloudinstance.com/s/AWmmg8En3knRfRE/preview

Instead, I get a grey screen, and when I go digging in the web browser console I find the error that the item returned a 404 error from the webserver. This happens on Firefox, Edge and Chrome.

This is an odd one and it has been plaguing me a for a little while across NC25, 26 and 27. Honestly I’d be more inclined to be a misconfiguration issue than a bug, as I can’t find any bugs of people having the same issue and someone would have been bound to cross it by now. The annoying this I can’t seem to produce any error in the nextcloud or the nginx logs. Just the nginx access log says that it happened.

e.g.

 [11/Jul/2023:15:20:53 -0400] "GET /s/AWmmg8En3knRfRE/preview HTTP/2.0" 404 2 "-" "Mozilla/5.0 (Windows NT 10.0; rv:114.0) Gecko/20100101 Firefox/114.0"

If I had to guess, I’d say it was a webserver misconfiguration issue. But what do you guys think?

Nextcloud version (eg, 20.0.5): 27.0.0
Operating system and version (eg, Ubuntu 20.04): Ubuntu 22.04.02
Apache or nginx version (eg, Apache 2.4.25): nginx/1.25.0
PHP version (eg, 7.4): 8.2.8

Is this the first time you’ve seen this error? (Y/N):Y

Steps to replicate it:

  1. Share an image
  2. Go to the direct link (i.e /s/ABCDEF/preview

The output of your Nextcloud log in Admin > Logging:

Nothing relevant triggered by the event

The output of your config.php file in /path/to/nextcloud (make sure you remove any identifiable information!):

<?php
$CONFIG = array (
  'activity_expire_days' => 14,
  'auth.bruteforce.protection.enabled' => true,
  'session_lifetime' => 43200,
  'auto_logout' => true,
  'remember_login_cookie_lifetime' => 86400,
  'token_auth_activity_update' => 60,
  'blacklisted_files' =>
  array (
    0 => '.htaccess',
    1 => 'Thumbs.db',
    2 => 'thumbs.db',
  ),
  'cron_log' => true,
  'preview_max_memory' => 4096,
  'preview_max_filesize_image' => 256,
  'enable_previews' => true,
  'enabledPreviewProviders' =>
  array (
    0 => 'OC\\Preview\\PNG',
    1 => 'OC\\Preview\\JPEG',
    2 => 'OC\\Preview\\GIF',
    3 => 'OC\\Preview\\BMP',
    4 => 'OC\\Preview\\XBitmap',
    5 => 'OC\\Preview\\Movie',
    6 => 'OC\\Preview\\PDF',
    7 => 'OC\\Preview\\MP3',
    8 => 'OC\\Preview\\TXT',
    9 => 'OC\\Preview\\MarkDown',
    10 => 'OC\\Preview\\HEIC',
    11 => 'OC\\Preview\\TIFF',
    12 => 'OC\\Preview\\MKV',
    13 => 'OC\\Preview\\MP4',
    14 => 'OC\\Preview\\AVI',
    15 => 'OC\\Preview\\Image',
  ),
  'trusted_proxies' =>
  array (
    0 => '127.0.0.1',
    1 => '::1',
  ),
  'filesystem_check_changes' => 0,
  'filelocking.enabled' => 'true',
  'htaccess.RewriteBase' => '/',
  'integrity.check.disabled' => false,
  'knowledgebaseenabled' => false,
  'passwordsalt' => 'REDACTED',
  'secret' => 'REDACTED',
  'trusted_domains' =>
  array (
    0 => 'REDACTED',
  ),
   'datadirectory' => '/var/server/nextcloud/data',
  'dbtype' => 'pgsql',
  'version' => '27.0.0.8',
  'overwrite.cli.url' => 'REDACTED',
  'overwriteprotocol' => 'https',
  'dbname' => 'nextclouddb',
  'dbhost' => 'localhost',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'dbuser' => 'REDACTED',
  'dbpassword' => 'REDACTED',
  'installed' => true,
  'mail_smtpmode' => 'smtp',
  'mail_sendmailmode' => 'REDACTED',
  'mail_from_address' => 'REDACTED',
  'mail_domain' => 'REDACTED',
  'mail_smtpauthtype' => 'REDACTED',
  'mail_smtpauth' => 1,
  'mail_smtphost' => 'REDACTED',
  'mail_smtpport' => 'REDACTED',
  'mail_smtpname' => 'REDACTED',
  'mail_smtppassword' => 'REDACTED',
  'maintenance' => false,
  'log_type' => 'file',
  'logfile' => '/var/log/nextcloud/nextcloud.log',
  'logdateformat' => 'F d, Y H:i:s',
  'logtimezone' => 'REDACTED',
  'has_rebuilt_cache' => true,
  'memcache.locking' => '\\OC\\Memcache\\Redis',
  'memcache.local' => '\\OC\\Memcache\\APCu',
  'memcache.distributed' => '\\OC\\Memcache\\Redis',
  'redis' =>
  array (
    'host' => '/var/run/redis/redis-server.sock',
    'port' => 0,
    'dbindex' => 0,
    'timeout' => 1.5,
    'password' => 'REDACTED',
  ),
  'theme' => '',
  'default_phone_region' => 'REDACTED',
  'updater.release.channel' => 'stable',
  'instanceid' => 'REDACTED',
  'allow_local_remote_servers' => true,
  'app_install_overwrite' =>
  array (
    0 => 'apporder',
    1 => 'keeweb',
    2 => 'ocsms',
    3 => 'contacts',
    4 => 'maps',
    5 => 'drawio',
    6 => 'ocr',
    7 => 'carnet',
    8 => 'cookbook',
    9 => 'music',
    10 => 'side_menu',
    11 => 'files_texteditor',
    12 => 'bookmarks',
    13 => 'breezedark',
    14 => 'files_markdown',
    15 => 'workflow_media_converter',
    16 => 'end_to_end_encryption',
    17 => 'richdocumentscode',
    18 => 'epubreader',
    19 => 'video_converter',
    20 => 'memories',
    21 => 'news',
  ),
  'data-fingerprint' => 'REDACTED',
  'memories.exiftool' => '/var/www/nextcloud/apps/memories/exiftool-bin/exiftool-amd64-glibc',
  'memories.gis_type' => 2,
  'loglevel' => 2,
  'memories.vod.ffmpeg' => '/usr/bin/ffmpeg',
  'memories.vod.ffprobe' => '/usr/bin/ffprobe',
  'memories.vod.path' => '/var/www/nextcloud/apps/memories/exiftool-bin/go-vod-amd64',
  'memories.vod.disable' => false,
  'memories.vod.tempdir' => '/tmp',
);

The output of your Apache/nginx/system log in /var/log/____:

Nothing triggered by event

Here is my webserver configuration

upstream php-handler {
#    server 127.0.0.1:9000;
     server unix:/var/run/php/php8.2-fpm.sock;
}

# Set the `immutable` cache control options only for assets with a cache busting `v` argument
map $arg_v $asset_immutable {
    "" "";
    default "immutable";
}

server {
    listen 80;
    listen [::]:80;
    server_name REDACTED;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # Enforce HTTPS
    return 301 https://$server_name$request_uri;
}

server {
     listen 127.0.0.2:443 quic reuseport; # QUIC
     listen 127.0.0.2:443 ssl http2;             # TCP
     listen [::1]:443 quic reuseport; # QUIC
     listen [::1]:443 ssl http2;             # TCP

#    listen 127.0.0.2:443 ssl http2; # TCP listener for HTTP/1.1
#    listen [::1]:443 ssl http2;
    server_name REDACTED;

    # Path to the root of your installation
    root /var/www/nextcloud/;

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/
    ssl_certificate REDACTED;
    ssl_certificate_key REDACTED;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # HSTS settings
    # WARNING: Only add the preload option once you read about
    # the consequences in https://hstspreload.org/. This option
    # will add the domain to a hardcoded list that is shipped
    # in all major browsers and getting removed from this list
    # could take several months.
    #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;

    # set max upload size and increase upload timeout:
    client_max_body_size 512M;
    client_body_timeout 300s;
 fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    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 text/javascript application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/wasm 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;

    # Pagespeed is not supported by Nextcloud, so if your server is built
    # with the `ngx_pagespeed` module, uncomment this line to disable it.
    #pagespeed off;

    # The settings allows you to optimize the HTTP2 bandwitdth.
    # See https://blog.cloudflare.com/delivering-http-2-upload-speed-improvements/
    # for tunning hints
    client_body_buffer_size 512k;

    # HTTP response headers borrowed from Nextcloud `.htaccess`
    add_header Referrer-Policy                      "no-referrer"   always;
    add_header X-Content-Type-Options               "nosniff"       always;
    add_header X-Download-Options                   "noopen"        always;
    add_header X-Frame-Options                      "SAMEORIGIN"    always;
    add_header X-Permitted-Cross-Domain-Policies    "none"          always;
    add_header X-Robots-Tag                         "noindex, nofollow" always;
    add_header X-XSS-Protection                     "1; mode=block" always;
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;
    add_header Alt-Svc 'h3=":443"; ma=86400';                                                   # Add Alt-Svc header to negotiate HTTP/3

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

    # Add .mjs as a file extension for javascript
    # Either include it in the default mime.types list
    # or include you can include that list explicitly and add the file extension
    # only for Nextcloud like below:
    include mime.types;
    types {
        text/javascript js mjs;
    }

    # Specify how to handle directories -- specifying `/index.php$request_uri`
    # here as the fallback means that Nginx always exhibits the desired behaviour
    # when a client requests a path that corresponds to a directory that exists
    # on the server. In particular, if that directory contains an index.php file,
    # that file is correctly served; if it doesn't, then the request is passed to
    # the front-end controller. This consistent behaviour means that we don't need
   # to specify custom rules for certain paths (e.g. images and other assets,
    # `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
    # `try_files $uri $uri/ /index.php$request_uri`
    # always provides the desired behaviour.
    index index.php index.html /index.php$request_uri;

    # Enable QUIC and HTTP/3
    quic_retry on;
    quic_gso on;
    ssl_early_data on;

    # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
    location = / {
        if ( $http_user_agent ~ ^DavClnt ) {
            return 302 /remote.php/webdav/$is_args$args;
        }
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Make a regex exception for `/.well-known` so that clients can still
    # access it despite the existence of the regex rule
    # `location ~ /(\.|autotest|...)` which would otherwise handle requests
    # for `/.well-known`.
    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in `.htaccess` that concern `/.well-known`.

        location = /.well-known/carddav { return 301 /remote.php/dav/; }
        location = /.well-known/caldav  { return 301 /remote.php/dav/; }

        location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
        location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

        # Let Nextcloud's API for `/.well-known` URIs handle all other
        # requests by passing them to the front-end controller.
        return 301 /index.php$request_uri;
    }

    # Rules borrowed from `.htaccess` to hide certain paths from clients
    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

    # Ensure this block, which passes PHP files to the PHP process, is above the blocks
    # which handle static assets (as seen below). If this block is not declared first,
    # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
    # to the URI, resulting in a HTTP 500 error response.
    location ~ \.php(?:$|/) {
        # Required for legacy support
        rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;

        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set $path_info $fastcgi_path_info;

        try_files $fastcgi_script_name =404;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $path_info;
        fastcgi_param HTTPS on;

        fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
        fastcgi_param front_controller_active true;     # Enable pretty urls
        fastcgi_pass php-handler;

        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;

        fastcgi_max_temp_file_size 0;
    }

    # Serve static files
    location ~ \.(?:css|js|svg|gif|png|jpg|ico|wasm|tflite|map)$ {
        try_files $uri /index.php$request_uri;
        add_header Cache-Control "public, max-age=15778463, $asset_immutable";
        access_log off;     # Optional: Don't log access to assets

        location ~ \.wasm$ {
            default_type application/wasm;
        }
    }

    location ~ \.woff2?$ {
        try_files $uri /index.php$request_uri;
        expires 7d;         # Cache-Control policy borrowed from `.htaccess`
        access_log off;     # Optional: Don't log access to assets
    }

    # Rule borrowed from `.htaccess`
    location /remote {
        return 301 /remote.php$request_uri;
    }

    location / {
        try_files $uri $uri/ /index.php$request_uri;
    }

    location ^~ /push/ {
        proxy_pass http://127.0.0.1:7867/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    limit_req   zone=one  burst=200 nodelay;
}

Thank you!

Never did solve this one, if anyone has any ideas?

Finally figured out this one. As soon as I saw that this was a feature I knew it had to be it…

So the trick to simply apply the “Edit” or more specifically the “update” permission on the file and it will be authorized to display from the direct link. Very strange. I’m all for increased security, but I question, why does it need an update permission? Shouldn’t read suffice?