RewriteRule ^(.+/)?public-(.*) /redirect-url/ [R=301,L]
This would seem to do the opposite (sort of) of what you are trying to do. It redirects any URL that contains the string "public-". It needs to match any URL that does not start "public-" in the last path segment and also ends with .pdf
.
Also, this should not be a 301 (permanent) redirect, otherwise, users who have previously visited these URLs and been redirected will find it hard to visit the URL when they are authorised to do so (but see note below[*1]).
You can negate regular expressions in mod_rewrite simply by prefixing them with !
. So !foo
would match any URL that does not contain "foo".
Try the following instead, to redirect all non-public .pdf
files to the home page:
RewriteRule !^(.+/)?public-[\w-]\.pdf$ / [R,L]
This unconditionally redirects every URL that does not match the given pattern. The character class [\w-]
matches the characters a-z
, A-Z
, 0-9
, _
and -
. So, only alphanumeric characters plus underscore and hyphen are permitted in your PDF filenames.
If it should only redirect requests that would map to an actual file then you need an additional condition (if you are placing these directives at the top of the file). For example:
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule !^(.+/)?public-[\w-]\.pdf$ / [R,L]
Or, place these directives after the WordPress front-controller.
Some of file are public but theirs a files cannot be access. but when you logged in all file are accessable
[*1] Although I don't know how you were hoping to implement that when you are unconditionally redirecting all these requests in .htaccess
?
Bit of an aside, but ... you shouldn't normally "block" requests by redirecting to the homepage. And nor would you use mod_rewrite to block access to specific files on the filesystem. mod_rewrite in .htaccess
primarily deals with URLs, not filesystem paths.
To specifically block access to .pdf
files (ie. serve a 403 Forbidden), but allow public-
.pdf
files then you would use mod_authz_core (Apache 2.4+) inside a <FilesMatch>
container. For example:
<FilesMatch "^(?!public-).+\.pdf$">
Require all denied
</FilesMatch>
The above regex uses a negative lookahead to match all .pdf
files that do not start with "public-".
public-
prefix in the name, go to a404
not found error page? Have you thought about adding password protection instead for files that shouldn't be available to the public? In other words, why have files on a server if you don't want to serve them?