Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
The easiest way is to place a constant in the index.php and check in the other php files if this constant exists. If not, let the script die.index.phpdefine('APP', true);various.phpif(!defined('APP')) die();
This is what the map of my website looks like:root: -index.php -\actions\ (various php files inside and a .htaccess) - \includes\ (various php files inside and a .htaccess) - .htaccessI know that if I use "deny from all" in actions and includes directories, the files in them will be secured from direct access.Now, my actions folder has many php files that are called byindex.php(forms). I have "deny from all" in.htaccessinside\actions, but then I have the forbiden access to that files.So, how can I protect the files from direct url access but have the exception that can be called fromindex.php?
Protect php files from direct access
You're seeing this the wrong way round. You don't want to redirect a request for a .php file to a clean address, because you never want the user to see the .php in the first place. Instead you need to take a request which does not end with .php and then check to see whether the file (underneath the surface) actually has a .php extension. Then, if that's the case, silently rewrite the request to add the .php extension, so that the user never needs to see the extension.Try the following:RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^([a-zA-Z0-9_-]+)/?$ /$1.php [QSA]The RewriteCond checks to see whether the request (tacked on to the end of the DOCUMENT_ROOT path) forms a valid filename once ".php" is added to the end of it. If so, then the RewriteRule is allowed to silently rewrite the request so that ".php" is added to the request path. The QSA flag tells mod_rewrite to append the existing query string to the end of the new request path, so your GET variables should be preserved.Note that DOCUMENT_ROOT may or may not have a trailing slash already, so you might need to get rid of the slash before$1in the RewriteCond.As for query string parameters, mod_rewrite cannot handle an indefinite number of variables, so you would need to give an explicit request pattern in your question before a mod_rewrite solution could offer a way to map it to a query string.
I have looked at these solutions and none of them actually work properly on my end:mod_rewrite to remove .php but still serve the .php file?How to remove file extension from website address?How to use Apache Mod_rewrite to remove php extension, while preserving the GET parameters?and they just don't do the following, which is what I need done:1) remove .php extension from files and instead of /index.php display /index2) preserve GET parameters (which I read and store in session cookies while the file is being loaded, in the header), so instead of /index.php?a=1&b=2 display maybe /index/a1/b23) work on subdomains and https:// without messing up the URL completely or ending up in an infinite loop or something...Does anyone have a clue how to put together these rules so they cover the 3 points above correctly?This is what I'm working with as a starting point:RewriteCond %{THE_REQUEST} (\.php(.*)\sHTTP/1) RewriteRule ^(.+)\.php$ /$1 [R=301,L,QSA]
mod_rewrite to remove .php extension AND preserve GET parameters
You can use theSetEnvIfvariable in the .htaccess file to check if a certain Cookie value is set. For example (this isn't very secure, but just for illustration):AuthType Basic AuthName "Protected Login" AuthUserFile "/path/to/.htpasswd" AuthGroupFile "/dev/null" SetEnvIf Cookie PHPSESSID=.* PASS=1 Order deny,allow Deny from all Allow from env=PASS Require valid-user Satisfy anyThe lineSetEnvIf Cookie PHPSESSID=.* PASS=1checks if a Cookie is set with a PHP session id and if so, that is enough toSatisfythe authentication process and theAllow from env=PASSmakes it skip the login prompt if this is true.Again, this example is not very safe as a PHP session cookie is already set whensession_start()is called without a succesful authentication attempt, so it would be better to set a more cryptical/random cookie value that's hard to guess. For example:SetEnvIf Cookie AJNC3Z921dmc4O8P2 PASS=1That way, if you set a cookie value ofAJNC3Z921dmc4O8P2upon succesful authentication through PHP, this will be enough to pass the authentication process. Make sure to set a proper cookie expiration time though to avoid people from being able to pass the login prompt for a prolonged period.
Here's the layout:web root - admin (dir) - index.php - js - img - other files / dirs - dir - filesUntil now, I protected the admin dir with .htaccess passwd because I want full access control for all files in that dir (including js scripts, jpg, pdf etc). On the other hand, my custom CMS provides authentication using PHP sesssion / cookie for other URLs. What I want to accomplish is to use the same PHP authentication for the .htaccess protected dir, avoiding the popup prompt for user / password for already PHP authenticated users. In summary:I want the admin dir to use the .htaccess rules for authenticationIf a user is already authenticated using PHP (login in a HTML form, on a non-protected file), bypass the second .htaccess authentication process when accessing the admin dir contentIf a non PHP authenticated user tries to access content in the admin dir, the HTTP auth popup should be triggeredMost of the stuff that I've read suggest to move the admin dir outside the web root and access the files from a PHP script with readfile, which I don't want to do. There's dynamic content on that dir, as well as static. I know that apache will trigger the auth popup before loading any resources so the question is how to make apache aware that the user is already authenticated. Any other suggestion / workaround?
PHP and .htaccess authentication solution
No problem. Just look at the example fromApache's documentation(a place where you might want to look, if you happen to have an apache-related question in the future). For example:# Mark requests for the AJAX call SetEnvIf Request_URI "^/myajaxscript\.php.*$" dontlog SetEnvIf Request_URI "^/myotherajaxscript\.php$" dontlog # Log what remains CustomLog logs/access_log common env=!dontlog
I'm working on a site where the main idea is to do a lot ofxmlHttpRequestsin a loop (or loop like construct). But the thing is that every time I access the file on my server from thejavascriptit is logged inaccess log on the server. Over time the access log file gets so big it slows down the further requests.Is there a way to tell the apache (I guess) not to log the access to this file if its correct? (I'm sending a get with a password (always different) to this file.) The access to the file will be from different IPs. I don't want to stop all the logging, just the "approved" one.
Prevent (stop) Apache from logging specific AJAX / XmlHttpRequests?
Add the following into an .htaccess file:<Files *.mp4> ForceType application/octet-stream Header set Content-Disposition attachment </Files> <Files *.pdf> ForceType application/octet-stream Header set Content-Disposition attachment </Files>
How do I create Apache directives in a.htaccessfile that forces.mp4and.pdfto download? Currently they appear within the browser window. Instead, I would like a download file dialog box to appear.
Apache directive for file downloads
You can't have RewriteMap in an .htaccess file:http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritemapOnly usable in server config (like httpd.conf) and your virtual host conf files.
I have a map file in this format233 Alabama/Phenix-City/Ridgebrook 237 Alabama/Ft.-Mitchell/Riverside-EstatesI have the following .htaccess script. I'm getting a 500 Internal Server Error when the page in question is hit.RewriteEngine On RewriteBase / Options +FollowSymLinks RewriteMap examplemap txt:/var/www/html/site.com/key_pair.txt RewriteRule community.php?(.*) ${examplemap:$1} [R]When I pass the following URL I wish for it to be rewritten as follows.http://example.com/community.php?comm_id=233should be rewritten like thishttp://example.com/Alabama/Phenix-City/RidgebrookAny thoughts?
Error 500 when I have RewriteMap in .htaccess
Write your .htaccess like this:RewriteCond %{HTTP_HOST} (www\.)?domain\.(org|net|com)$ [NC] RewriteCond %{REQUEST_URI} !^/*no_redirect_dir/ [NC] RewriteRule ^(.*)$ http://www.domain.info/$1 [R=301,L]HTTP_HOST variable just has domain name, no http/https information.
I am trying to redirect multiple domains to a single domain (which is working fine) but i want one directory to not redirect or change the main domain url.here is my .htaccess code it works fine until herethis one is working<pre> RewriteCond %{HTTP_HOST} ^http(s)?://(www.)?domain.com$ [OR] RewriteCond %{HTTP_HOST} ^http(s)?://(www.)?domain.net$ [OR] RewriteCond %{HTTP_HOST} ^http(s)?://(www.)?domain.org$ [OR] RewriteCond %{HTTP_HOST} ^domain.info$ [OR] RewriteCond %{HTTP_HOST} !^www.domain.info RewriteRule (.*) http://www.domain.info/$1 [R=301,L] </pre>but when i try to stop redirect of one specific directory byfull code<pre> RewriteCond %{HTTP_HOST} ^http(s)?://(www.)?domain.com$ [OR] RewriteCond %{HTTP_HOST} ^http(s)?://(www.)?domain.net$ [OR] RewriteCond %{HTTP_HOST} ^http(s)?://(www.)?domain.org$ [OR] RewriteCond %{HTTP_HOST} ^domain.info$ [OR] RewriteCond %{HTTP_HOST} !^www.domain.info [OR] RewriteCond %{REQUEST_URI} !^/no_redirect_dir/ RewriteRule (.*) http://www.domain.info/$1 [R=301,L] </pre>it all stops working :( with an error that page is not redirecting correctly.extra code causing error<pre> RewriteCond %{HTTP_HOST} !^www.domain.info [OR] RewriteCond %{REQUEST_URI} !^/no_redirect_dir/ </pre>any help would be highly appreciated.thank you!
How to redirect multiple domains to another domain except 1 directory using htaccess?
The URL part of an ErrorDocument directive should either start with a leading slash, which indicates a path that's relative to your DocumentRoot, or it should be a full URL (if you want to use an external document).You shouldn't need the RewriteEngine and RewriteRule directives at all here.So, assuming your notfound.html is at the root level of your site, your directive should look like:ErrorDocument 403 /notfound.html
I want to redirect any 403 using .htaccess, but it does not seem to work.Options +FollowSymlinks RewriteEngine on ErrorDocument 403 notfound.html RewriteRule notfound.htmlAll help appreciated.Thanks Jean
redirect 403 error using .htaccess
RewriteRule ^index.php /en/home [R=301]
Currently my htaccess file contains this rule, to redirect website.org/index.php towebsite.org/en/homeRewriteRule index.php /en/home [R=301]However, currently also otherindex.phppages in deeper folders redirect! e.g.website.org/folder/index.phpredirects towebsite.org/en/homeHow can I have that rule exclusively apply to the root, and no deeper folders? Thanks very much.
How to redirect index.php to another page properly via .htaccess?
<VirtualHost *:80> ServerName zf_cms.local DocumentRoot /Users/kjye/Sites/zf_cms/public SetEnv APPLICATION_ENV "development" <Directory /Users/kjye/Sites/zf_cms/public> Options +Indexes +FollowSymLinks +ExecCGI DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory>This turns out to work under mac os. thanks for all the help and comment.
I am trying to get Zend Framework's quickstart tutorial up and running, but i ran into .htaccess issue. It seems if i remove the .htaccess file, the project runs fine, but if i leave it in there it throws a 403 Forbidden. The .htaccess is the default file generated by Zend Framework console command. Here is the .htaccess:RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L]This is under Mac OS X 10.6.5mod_rewrite is on AllowOveride AllHere is my virtual host info<VirtualHost *:80> ServerName zf_cms.local DocumentRoot /Users/kjye/Sites/zf_cms/public SetEnv APPLICATION_ENV "development" <Directory /Users/kjye/Sites/zf_cms/public> Options +Indexes +FollowSymLinks +ExecCGI DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>I fixed it by adding "Options +Indexes +FollowSymLinks +ExecCGI" Thanks for viewing.
.htaccess throws 403 Forbidden / Zend Framework quickstart project creation (Mac OS X 10.6.5)
use this:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /folder/index.php/$1 [L]
This is what my.htaccesslooks like. The.htaccessis sitting in/www/scriptsdirectory which is the parent of codeigniter'ssystemdirectory and which also containsindex.php. I have enabledmod_rewritein my Apache 2.2.x. This is on Ubuntu 9.10 server.I followed thislink, but it does not work. Is there anything I need to do in apache2, any specific configuration so that this works?RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [QSA,L]
CodeIgniter - How to hide index.php from the URL
Try this:<Files "*.json"> Order Deny,Allow Deny from all </Files>
I have a directory with files like:/files/archive.01.json /files/archive.02.json /files/archive.03.json /files/hello.phpI need the .htaccess to block access to all .json files in that directory. Any ideas?
Blocking specific extensions in htaccess
+100You can set environment variables with mod_rewrite as well. Actually, you already did that (seeenv/Eflag).I can’t test it with mod_negotiation myself, but the following should work and set theprefer-language:RewriteCond %{QUERY_STRING} ^((?:[^&]&)*)language=(en|fr|no)&?([^&].*)?$ RewriteRule ^ %{REQUEST_URI}?%1%3 [L,CO=language:%2,R] RewriteCond %{HTTP_COOKIE} (^|[,\s])language=([^\s,;]+) RewriteRule ^ - [L,E=prefer-language:%2] SetEnvIf REDIRECT_prefer-language (.+) prefer-language=$1But it would be far easier if you put the language identifier into the URL path like/en/…:SetEnvIf Request_URI ^/(en|fr|no)/ prefer-language=$1 SetEnvIf REDIRECT_prefer-language (.+) prefer-language=$1I don’t know if you need the additional/secondSetEnvIfvariable.
I'm trying to implement language switching in .htaccess, and the only thing left now is to handle clients which don't support cookies. To do that, I must setprefer-languagewhen the user clicks a link with alanguageparameter.RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} (?:^|&)language=(en|fr|no) RewriteRule ^(.*)$ $1? [cookie=language:%1:.example.com,env=language:%1,R] SetEnv prefer-language $languageThe problem is with the last line - The value is always set to empty. It works if I hardcode it, but not if I try to refer to a variable. Is there some special syntax to refer to environment variables in this context, or is there some other way to setprefer-language?Edit: Cross-posted toApache users list.
How to use SetEnv with a URL parameter
Maybe using QSA in your rewriterules, like this :RewriteRule .* index.php?kohana_uri=$0 [PT,QSA,L]See themanual of mod_rewrite(quoting) :'qsappend|QSA' (query string append)This flag forces the rewrite engine to append a query string part of the substitution string to the existing string, instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.Might help (not tested in your particular case, but I remember have used this some time ago, for some kind of problem like this one)
After uploading my Kohana project to my Godaddy server, I noticed my standard .htaccess file wasn't working sufficiently to provide the clean URLs. After some guidance, I ended up with the following rule:RewriteRule .* index.php?kohana_uri=$0 [PT,L]This got my nice-URLs working again, but today I find out that it may be breaking my internal search-engine, which also uses GET-style variables:/search?terms=phpThe values aren't being found by the scripts. They are on my development-server which doesn't have the modified RewriteRule, but not on the Godaddy server which does use the RewriteRule.Am I right in assuming that rule is breaking any scripts ability to read from $_GET, and if so how can I remedy this?
Kohana, .htaccess, and $_GET
You have to combine theRewriteConddirectives with AND instead of OR as you want to redirect if both conditions are true (therefor the IP address is neitherXnorY). So try this:RewriteEngine on RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.89$ RewriteCond %{REMOTE_ADDR} !^213\.45\.67\.89$ RewriteRule ^ http://www.example.com/ [R]
I want to protect some subdomains from the public. Restriction should be done against a whitelist of IPs. Infinite loop due to the redirect is not a problem as its not the www-domain.I tried thishttp://discussions.apple.com/message.jspa?messageID=2411725, but couldnt get it to work.However I did try this firstRewriteEngine on RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.89$ [OR] RewriteCond %{REMOTE_ADDR} !^213\.45\.67\.89$ RewriteRule ^/.* http://www.mydomain.com [R].. but didnt work.What am I doing wrong ?
Redirect all IPs except those whitelisted
Your ssl certificate is propably self-signed, try using curl with the-k(--insecure) option which disables ssl verification.
When I try to make up a.htaccessfile to redirect my www to non-www, I get some issues.RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]This is the.htaccessfile I've used, after using:curl -I https://wwwI get:curl: (51) Unable to communicate securely with peer: requested domain name does not match the server's certificate.But after usingcurl -I http://wwwI get a 301 redirection, which was my intended case but it redirects to HTTPS www.The problem of that is that I get a DNS error when I'm visiting it on the internet.How can I possibly fix this?
Curl: (51) error when trying to check whether or not my website redirects correctly
Super easy tool here:http://www.htaccesstools.com/redirection-by-language/Makes life incredibly easy for htaccess redirects based on the browser's language.Example:RewriteEngine on RewriteCond %{HTTP:Accept-Language} (fr) [NC] RewriteRule .* /fr/index.html [L] RewriteCond %{HTTP:Accept-Language} (en) [NC] RewriteRule .* /en/index.html [L] RewriteCond %{HTTP:Accept-Language} (de) [NC] RewriteRule .* /de/index.html [L]This is a hard redirect, the browser's location bar will indeed show the new page. Though, this is better for UX than an internal redirect masking the URL.To answer your question, it is highly regarded that an index.html provides the best UX. However, that's essentially because people have come to expect this in general (website.com/en/, website.com/fr/, etc.). SEO-wise, no, you wouldn't get dinged if you didn't follow that same structure.Best practice is to use your best guess (like the htaccess), and still offer a menu for switching languages. Plus, you'll also need a fallback for if the Accept-Language isn't actually defined (like going to /en/ by default). This could be a final line in the htaccess, or it could simply be anindex.htmlat the root level, where.htaccessis.Other than that, there's not a tremendous amount that goes into localization.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this questionMy website will be in 3 languages. French (fr) is the default language. The structure of the site is the following:Root directory (note: I'm not using php files, just plain html)/fr/ Index.html About-us.html Contact.html /en/ Index.html About-us.html Contact.html /de/ Index.html About-us.html Contact.htmlI got questions:What is the best practice to redirect users based on their web browser language? Via htaccess?Do I need a index.html page at root level (for SEO reason or any other reason) ? The French index.html perhaps?
Redirect users based on browser language (not in php) [closed]
You can use these rules with appropriateRewriteBase:RewriteEngine On RewriteBase /admin/ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ ?arg=$1 [L,QSA]
I have trying to figure out how to get working in subfolder "admin" the same thing which works in root dir, problem is I don't know how to do that.Currently I have:RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ ?arg=$1 [L,QSA] # / RewriteCond %{REQUEST_URI} !\.[[:alnum:]]+$ RewriteRule ^(.+[^/])$ /$1/ [R=301]Now it works like:http://example.com/pagetranslate intohttp://example.com/?arg=pageWhat I would like to do in addition is this:http://example.com/admin/pagetranslate intohttp://example.com/admin/?arg=pageI don't know at all how to make that happen, can somebody help me please?Thanks
htaccess rewrite rule for subfolder (nice url)
You cannot match schemehttp://inRewriteCond %{HTTP_HOST}.You can use this rule:RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC] RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=302,L]
We have just bought the .com extension for our domain and we are using ssl certificates on both of them:https://www.domain.net https://www.domain.comNow we would like to use the .com extensiononlyand redirect our users from the old domain to the new one using the htaccess file:http[s]://domain.net -------| http[s]://www.domain.net ---|---> https://www.domain.com http[s]://domain.com -------|I am not very familiar with htaccess so I tried:RewriteEngine On RewriteCond %{HTTP_HOST} ^http[s]?://(www\.)?domain\.com(.*)?$ RewriteRule ^(.*)$ http[s]?://www.domain.com/? [R,L]That obviously doesn't work!Any help would be greatly appreciated.
Htaccess redirect https to another https
The preferred method would be to read the request header, find the origin, check it in your server side code. If the domain is allowed to access the page, send back the origin domain in one singleAccess-Control-Allow-Originheader.Another pro: No other domain user would see the list of allowed domains. Every user would only see his own domain (if allowed).
header('Access-Control-Allow-Origin: http://splash.example.com'); header('Access-Control-Allow-Credentials: true');Hello again Stackoverflow!On my website, I have an ajax fileajax.php, where I need multiple (sub) domains to access it and fire requests.The problem is that it works forsplash.example.comandexample.comwith the solution posted above, and this in the request:$.ajax({ ... crossDomain: true, xhrFields: { withCredentials: true }, ... });But isn't there an easier way? 'Cause right now it isn't working forwww.example.com, even with the solution posted above.I've tried putting this in my htaccess:<IfModule mod_headers.c> Header add Access-Control-Allow-Origin "http://example.com" Header add Access-Control-Allow-Origin "http://www.example.com" Header add Access-Control-Allow-Origin "http://splash.example.com" Header set Access-Control-Allow-Credentials true </IfModule>but this didn't work somehow.Can you guys help me?
Access-Control-Allow-Origin for multiple domains, in an easier way
) in your dashboard, go to settings -> general and make surea) wordpress directory ->http://mydomain.com/wpb) site address ->http://mydomain.com2) move your index.php from subdirectory to the root (MOVE, don't just copy)3) edit your index.php to read/** Loads the WordPress Environment and Template */ require('./wp/wp-blog-header.php');where "wp" is your subdirectory4) delete any .htaccess file in the subdirectory5) add this to your .htaccess in the root# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPressUnder this setup, your wordpress installation will be located in /wp/ directory. Visitors will visit your site usinghttp://mydomain.com.If you want to have a good read-up on everything so you know exactly what you're doing, read thishttps://codex.wordpress.org/Giving_WordPress_Its_Own_Directory
I have a website on www.example.com. On that domain Wordpress website is in directorywp.So to access my wordpress website you should go to www.example.com/wp and that is the main website.In root i have index.html where you choose language and then go to Wordpress websiteWhat i need sounds simple! :) I want to removewpfrom url using .htaccess or whatever else could do the trick, so when browse Wordpress website it shouild work withoutwp!I must note that website must stay in wp folder!Is this achievable?
Remove directory name from url Wordpress
If you have a folder called "filesForAnyUser" and a folder where you have files only for admin, you need to make 2 htaccess files. One in "filesForAnyUser":AuthType Basic AuthName "restricted" AuthUserFile E:\\path\\to\\.htpasswd Require valid-userAnd one in the other directory:AuthType Basic AuthName "restricted" AuthUserFile E:\\path\\to\\.htpasswd Require user admin
I have a files server and I use mod_autoindex to server the files. I have a username and password in htaccess so only certain people can access the files. I have added another user to htpasswd but I would only like that user to access some of the files/folders.Here is my htaccess file now:AuthType Basic AuthName "restricted" AuthUserFile E:\\path\\to\\.htpasswd <Files "filesForAnyUser\\*"> Require valid-user </Files> <Files "*"> Require user admin </Files>I'm sure I am doing something wrong but I can't find any good documentation on this.
htaccess password protect files with different users
Can you replace your last rule with this:Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / # Check if mobile=1 is set and set cookie 'mobile' equal to 1 RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$) RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}] # Check if mobile=0 is set and set cookie 'mobile' equal to 0 RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$) RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}] # Skip next rule if mobile=0 [OR] if it's a file [OR] if /path/ RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$) [OR] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_URI} ^.*/path/.*$ RewriteRule ^ - [S=1] # Check if this looks like a mobile device RewriteCond %{HTTP_PROFILE} !^$ [OR] RewriteCond %{HTTP_X_WAP_PROFILE} !^$ [OR] RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC] # Check if we're not already on the mobile site RewriteCond %{HTTP_HOST} !^m\. # Check to make sure we haven't set the cookie before RewriteCond %{HTTP_COOKIE} !mobile=0(;|$) # Don't redirect "path" pages RewriteCond %{REQUEST_URI} !^.*/path/.*$ [NC] # Now redirect to the mobile site RewriteRule ^ http://m.example.com/ [R,L,NC]Edit by OP:The only problem was coming from the%{REQUEST_URI}that for a reason that I don't understand only works against^.*/path/.*$
I want this URL:http://www.example.com/path/antyhingto NOT be redirected.Here's what I have which is not working:RewriteCond %{REQUEST_URI} !^/path/.*$ [NC] RewriteRule ^ http://m.example.com/ [R,L]Currently it redirects all URLs tohttp://m.example.com/Here is the full code in my .htaccess file:RewriteBase / RewriteEngine On # Check if mobile=1 is set and set cookie 'mobile' equal to 1 RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$) RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}] # Check if mobile=0 is set and set cookie 'mobile' equal to 0 RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$) RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}] # Skip next rule if mobile=0 RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$) RewriteRule ^ - [S=1] # Check if this looks like a mobile device RewriteCond %{HTTP:x-wap-profile} !^$ [OR] RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR] RewriteCond %{HTTP:Profile} !^$ # Check if we're not already on the mobile site RewriteCond %{HTTP_HOST} !^m\. # Check to make sure we haven't set the cookie before RewriteCond %{HTTP:Cookie} !\mobile=0(;|$) # Don't redirect "path" pages RewriteCond %{REQUEST_URI} !^.+?/path/.*$ [NC] # Now redirect to the mobile site RewriteRule ^ http://m.example.com/ [R,L]
RewriteCond to exclude a path not working
The above answer of Jon Lin does not work. I found that Redirect may solve the problem as follows:#.htaccess at public_html Redirect /Hosts/directory/ http://dir.mydomain.com/
I have web site hosted on shared hosting account which is managed by CPanel. It allows to create unlimited sub-domains. I have the following situation:Suppose that my primary domain there is: mydomain.com My account's files are found on the hosting server at /home/myaccount/public_html I decided to make sub-domain named dir i.e dir.mydomain.com I created this sub-domain to use the following file: /home/myaccount/public_html/Hosts/directoryNow I, successfully, able to accesshttp://dir.mydomain.comHowever, I need to prevent the accesshttp://mydomain.com/Hosts/directoryand exclusively restrict the access to the sub-domain.How could I achieve this using .htaccess?The following is a copy of the code I use in the .htaccess file found in /home/myaccount/public_html/Hosts/directory<IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L] </IfModule> AddType audio/mpeg mp3 AddType text/xml xml
How to make sub folder exculsive access via sub domain only
Add a filerobots.txtin your website root directory with the following contents:User-agent: * Disallow: /users/download/idThis approach basically tells the Search Engine not to index/users/download/id.This doesn't mean every Search Engine will do that, but most of the modern Search Engines will take in consideration that file.
My project is an E-commerce website that It contains lot of static and dynamic pages. I want to hideonlyone page from Search engines. If any one search that text then it need not display on search engine like "Google","Yahoo" etc.http://www.mysitename.com/users/download/idThe above url need to hide in search engines.If any one searching my mysitename then above link also displaying in Google search as of now. what i can do for this ?
How to Hide a Particular website page URL from Search engines?
In your.htaccess, add the following line:Options -IndexesSeethe manualfor further details.
I have this current directory structuremyproject --> application --> assets --> data --> scripts --> styles --> system --> .htaccess --> favicon.ico --> index.phpI store my users uploaded images, videos on thedatadirectory, and it has this structure:data --> 5 --> thumbs --> user_images --> 6 --> thumbs --> user_images --> index.htmlI placedindex.htmlto prevent directory access. I can do this to all the data subdirectories to have the same effect, however is there a way to have this handled by .htaccess? I triedDeny from allrule in the .htaccess but it also won't allow me to use my images in my system. All I want to achieve is to prevent directory access (when direct access from URL) from my data directory. How is that?
prevent directory access
From your latest comment it looks like that you need to setRewriteBaseas well. As i mentioned in my first comment to your question, if you have your webserver's DocumentRoot and your webapp in separate folders, then this problem could arise. Try this:RewriteEngine on RewriteBase /~username/yourwebappfolder #rest of your rewrite conditions/rulesTo debug htaccess or other server configurations, check your server error_log, for mac lion it is in the file:/var/log/apache2/error_log
I've been doing some experiments with Yii, to see if it will suit my needs. The first thing I wanted to enable was the user-friendly URLs.What I want to achieve: to go from this URLwebapproot/index.php?r=site/contactto this URLwebapproot/contact.What I've done:Created an aplication using Yiic (php YiiRoot/framework/yiic.php webapp testdrive)Followed the steps 2 and 6 ofthis link from Yii's documentation("User-friendly URLs" and "Hiding index.php").What happens is that I keep getting a 404. Any ideas of what I did wrong?Below are some relevant excerpts to this question:[project root]/protected/config/main.php(...) 'urlManager'=>array( 'urlFormat'=>'path', 'showScriptName'=>false, 'rules'=>array( '<controller:\w+>/<id:\d+>'=>'<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', ), ), (...)[project root]/.htaccessRewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php/etc/apache2/httpd.conf(...) LoadModule rewrite_module libexec/apache2/mod_rewrite.so (...) <Directory [path to my web projects folder]> Options FollowSymLinks AllowOverride All Order deny,allow </Directory> (...)
User-friendly URLs in Yii
Just putRewriteCond %{REQUEST_URI} !^/media/videosabove your RewriteRule. It checks wether the URL starts with/media/videosand if it does so, the RewriteRule will not be met.
I was wondering how to exclude a subfolder from .htaccess redirect.I have an .htaccess file in the root of my old domain and I have the following in it:Options +FollowSymLinks RewriteEngine on RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]This of course redirects any traffic from the old domain to the new one. But I want to exclude a directory from this rule. Meaning www.olddomain.com/media/videos should not redirect to www.newdomain.com/media/videosThe reason I want the exclusion is because I'm hosting static files such as videos on a shared web server (old domain) and I'm keeping everything else the site needs on the new VPS server (new domain).
.htaccess redirect main domain but not sub subfolder
Is there a particular reason why you need to have two separate entries for your hosts? Seeing as they both use the same Log Files, and DocumentRoot, could you not add blah.com to the list of ServerAlias' ?So you would end up with the following configuration below:<VirtualHost *:80> ServerAdmin[email protected]ServerName v1.blah.com ServerAlias v1.blah.com blah.com DocumentRoot /home/blah/v1.blah.com <Directory /home/blah/v1.blah.com/> AllowOverride All Order allow,deny allow from all </Directory> AccessFileName .htaccess ErrorLog /home/blah/blah_logs/v1.blah.com.in-error_log CustomLog /home/blah/blah_logs/v1.blah.com.in-access_log common </VirtualHost>
I have a local dev Debx64 machine with a number of virtualhosts configured. the primary URL is set as<VirtualHost *:80> ServerAdmin[email protected]ServerName blah.com ServerAlias blah.com DocumentRoot /home/blah/v1.blah.com <Directory /home/blah/v1.blah.com/> AllowOverride All Order allow,deny allow from all </Directory> AccessFileName .htaccess ErrorLog /home/blah/blah_logs/v1.blah.com.in-error_log CustomLog /home/blah/blah_logs/v1.blah.com.in-access_log common </VirtualHost>and that redirects to the primary operating VH<VirtualHost *:80> ServerAdmin[email protected]ServerName v1.blah.com ServerAlias v1.blah.com DocumentRoot /home/blah/v1.blah.com <Directory /home/blah/v1.blah.com/> AllowOverride All Order allow,deny allow from all </Directory> AccessFileName .htaccess ErrorLog /home/blah/blah_logs/v1.blah.com.in-error_log CustomLog /home/blah/blah_logs/v1.blah.com.in-access_log common </VirtualHost>I have a .htaccess set up on v1.blah.com to parse .html as .phpOptions +ExecCGI AddHandler php-fcgi .php .html Action php-cgi /home/php5-fcgi <FilesMatch "^php5?\.(ini|cgi)$"> Order Deny,Allow Deny from All Allow from env=REDIRECT_STATUS </FilesMatch>This works fine if I access the URL as v1.blah.com, however if I access it as blah.com the .htaccess is not invoked and the .html is served as normal.What Am I missing? is there something in php.ini that needs to be changed?
htaccess with virtualhost not working
You can use this:RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ /$1 [L,R=301]The first line says: "if it's not a directory" (because then a trailing slash would have meaning). The second line says: redirect everything from start to the trailingslash and end to everything that was in there, without the trailing slash.Put your ownRewriteRulein there (below that one, not above) so your normal redirect still works after the trailing slash was removed.(this one will obviously work for/body/too, and not only for/face/.
The offending URLs are:(Doesn't work)http://alltheragefaces.com/face/surprised-wut/(Works)http://alltheragefaces.com/face/surprised-wutThe .htaccess rule I have for these types of URLs looks like:RewriteRule ^face/(.*)$ face.php?term=$1What can I do to make both of these URLs to go to the same page?
Trailing slash causes 404, can I fix using htaccess?
Not sure but give this a try:<Files ~ "\.php$"> ErrorDocument 404 /404.php </Files>Quote fromFiles Directivedocumentation:The <Files> directive limits the scope of the enclosed directives by filename.
I have a personalized page for 404 with htaccessErrorDocument 404 /404.phpIt works fine, but it takes everything .jpg, .js, .css etc...I would like it to just take the .php and do a normal 404 error for all others.I didn't find that option anywhere.Thank you very much.
Custom 404 error page -- for PHP pages only
You can use something like that:$.get(url,function(response){ content = $("#content",response); $('#newContentHere').append(content); });
I have a wordpress website and want to load my pages using jquery. I only want to load the content div, so I pass this the url like this:var url = $(this).attr('href') + "#content";Now when I try to load the page using ajax it loads the url without the #content part. Now it loads the complete page into my div instead of only the part that I want.Maybe it has something to do with my .htaccess:# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # RewriteRule ^index\.php$ - [L] RewriteRule ^(index\.php/?|intro.html)$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPressAny ideas?
Only load a part of a page with jquery
Most likely, your host is running a copy of PHP with the Suhoshin patch installed. This patch provides a large number of security and operational enhancements to PHP, including allowing the host to disable functions likeset_time_limit().There are other ways a host could disable theset_time_limit()function, but that's the most likely. (especially as you've already ruled out Safe Mode)Why would they disable this function? Because a PHP function that takes a long time to run also typically takes a lot of server resources; in a shared hosting environment, it is wise for the host to mitigate this kind of thing to avoid having a rogue script impact other users.What can you do about it?Firstly, are you sure you need to set the time limit? Do you know why your script takes that much time to run? Can you work around it? Perhaps doing a bit of profiling on your code might help you find the bottlenecks and speed up the program.Alternatively, if you really do need to set the time limit, you may need to ask your host to enable you to do so, or else upgrade your package or switch hosting providers.
I have a script where I have set:set_time_limit(0)but still getFatal error: Maximum execution time of 90 seconds exceeded in /home/Feed.php on line 234I've also tried setting:php_value max_execution_time 120in the .htaccess file but still can't stop this error - any ideas why this is not overriding?
set_time_limit(0) and "Maximum execution time" PHP
I've always used this method in my main root HTACCESS file and it works like a charm:<Files ~ "^.*\.([Hh][Tt][Aa])"> order allow,deny deny from all satisfy all </Files>More info on this method from one of my bookmarks:http://perishablepress.com/press/2008/05/20/improve-site-security-by-protecting-htaccess-files/
I added a .htaccess file to a folder to make it password protected. I would like to prevent all users from being able to read that .htaccess file, because it reveals the location of my .htpasswd (I don't have permissions on this server to put this file outside of the html tree).I tried the suggestions athttp://www.javascriptkit.com/howto/htaccess8.shtml, but I can still read my .htaccess on a web browser. Here is my .htaccess:AuthName "Restricted Area" AuthType Basic AuthUserFile /home/www/users/mylogin/HTML/some_hidden_dir/.htpasswd AuthGroupFile /dev/null require valid-user <Files .htaccess> order allow,deny deny from all </Files>What am I missing?
How do I prevent someone from reading my .htaccess file?
I finally figured it out. I indeed had to use the mod_rewrite engine. I was determined to have a solution which didn't involve me having to make extra files or directories.Same files, no extra directories, one .htaccess:# Case we are in the protected area! RewriteCond %{REQUEST_FILENAME} index.php [OR] RewriteCond %{REQUEST_FILENAME} !-f [OR] RewriteCond %{REQUEST_URI} ^(\/){1}$ RewriteCond %{REQUEST_FILENAME} !-d [OR] RewriteCond %{REQUEST_URI} ^(\/){1}$ RewriteCond %{HTTP_HOST} ^(protected)\.mydomain\.com$ RewriteRule ^(.*)$ admin.php%{REQUEST_URI} [L] #default rewrite RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] #only protect access to admin.php which is a symlink to index.php <FilesMatch "admin.php"> AuthUserFile .htpasswd AuthName EnterPassword AuthType Basic require valid-user </FilesMatch>
I'm trying to password protect a specific url using a .htaccess. Different urls point to the same files but have different workings. I now need to password protect only one url. I'm trying to do this using setenvif but it doesn't seem to work. I might not fully understand the purpose or use of the apache setenv module.This is my code what doesn't seem to workSetEnvIfNoCase Host "topasswordprotect\.domain\.com$" protecturl <IfDefine protecturl> Require valid-user AuthName "Please enter your name and password" AuthType Basic AuthUserFile .htpasswd </IfDefine>
How to do conditional .htaccess password protect
Welcome to SO!Provided, your Apache hasmod_setenvifenabled, add this to your.htaccessfile:# Site accessed via "example.de" or "example.cn" SetEnvIf Host "\.de$" SITE_LANGUAGE=de SetEnvIf Host "\.cn$" SITE_LANGUAGE=zh # URL dependent SetEnvIf Request_URI "^/de/" SITE_LANGUAGE=de SetEnvIf Request_URI "^/cn/" SITE_LANGUAGE=zhThen, in your PHP script you can querySITE_LANGUAGE:switch($_SERVER['SITE_LANGUAGE']) { case 'de': // german stuff case 'zh': // chinese stuff }
i'm using Joomla with the JoomFish translation component. This website has german and chinese translations. What i'm trying to figure out is how to get the .de domain to default to the german language translation ( which would load if visited as domain.com/de or domain.com/cn ).Does anyone know a way to do this with maybe .htaccess ( some kind of redirect )? Or possibly PHP? Maybe set some kind of session variable based on the domain (PHP_URL_HOST) ?Right now i have apache2 setup with the wwww.domain.com as the main virtual host, and the .de and .cn as aliases.
How to default to another language based on domain
Try this:RewriteRule ^123.html.? 123.html? [L]Note how the second url ends with a?, this removes the query string.Source:http://wiki.apache.org/httpd/RewriteQueryString
i want to remove a parameter after the true url then redirection to the same url without this parameterexample :i want to remove the parameter "r" fromhttp://www.mysite.com/123.html?r=1and redirection tohttp://www.mysite.com/123.htmlusing htaccess and 301 redirectthank you
removing parameters from url
+100Key solution:wildcard subdomains.This allows you to make*.domain.compoint to your server.From your example, let's say we enabled wildcard subdomains fordomain.comand we want to provide user subdomains, such ashttp://username.domain.com. You'd have something like this:RewriteCond %{HTTP_HOST} ^((?!www.)[^.]+)\.domain\.com$ [NC] RewriteRule ^(.*)$ /%1/$1 [L]wherehttp://username.domain.com/xxxwould point to/username/xxx.Note that this example has been reduced and simplified as much as possible for the explanation. You'd maybe need other rules, depending on your context, to handle main domain and other conditions.
I wonder, how does tumblr doing profile url like this:http://www.username.tumblr.com/ http://username.tumblr.com/I know we can change the profile urlhttp://www.website.com/profile.php?user=usernametohttp://www.website.com/usernameusing the followingRewriteRuleRewriteRule ^([^/]+)/?$ profile.php?user=$1 [L,QSA,NC]I don't know how tumblr doing those profile urls.How can we make user profile urls like this:http://www.username.website.com/ http://username.website.com/I have a VirtualHost.
How to make a tumblr style profile url
There are two ways that I would do this. Both are ways of adding 'C:\xampp\htdocs\k2' to your include pathUse.htaccessAdd this line to you.htaccessfile in the web root. You can add other directories as desiredphp_value include_path '.;C:\xampp\php\PEAR;C:\xampp\htdocs\k2'Makse sure Apache is configured to allow htacess to work:Number 4If you have some "config" file that is always included, you can add this line to it to set the include pathset_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\k2');This makes your code more portable than using relative or absolute path, since there is only one place to make changes when file structures change.
I have created a website using mvc framework, but I cant include php files in files that are from another folder. For example, I have model, view, controller and core folders, if I do the followingrequire 'Core/User.php'; in a view file in view folder, then I get the following error:Warning: require(Core/User.php): failed to open stream: No such file or directory in C:\xampp\htdocs\k2\View\customer-management.php on line 2 Fatal error: require(): Failed opening required 'Core/User.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\k2\View\customer-management.php on line 2I've tried using../Core/User.php, but the application becomes too messy and i need a cleaner way of doing this, perhaps working with php.ini or .htaccess to allow me to justinclude('Core/User.php');from another folder. Any help would be appreciated.
Require(): Failed opening required (include_path='.;C:\xampp\php\PEAR')
You can use a CDN such as Fastly or CloudFlare to perform SSL termination on your SendGrid click tracking links. They will terminate SSL (which will satisfy your HSTS config) and proxy the request to SendGrid for click tracking / redirection.There is some additional information here:https://sendgrid.com/docs/Classroom/Build/Add_Content/content_delivery_networks.htmlYou essentially want to configure Fastly / CloudFlare to proxy the requests, reach out to SendGrid support to have them verify and enable "SSL click tracking" for your account. Once they confirm that everything is set up as expected, you can then update the CNAME on your subdomain to point to the CDN provider rather than to SendGrid directly.You also have the option to set up Apache with mod_proxy to terminate SSL and proxy the requests directly to SendGrid.
So, almost a year ago, I setup HSTS on my site and submitted it to Google's preload list. Now, I have a problem because I whitelabeled my sendgrid link tracking, which relies on a cname for a subdomain of my site. So, those links fail and get aNET::ERR_CERT_COMMON_NAME_INVALIDerror in Chrome because the SSL certificate the browser receives is from SendGrid.Is there a way to resolve this? Chrome's preload list expects all my subdomains to be served over SSL with a cert tied to my actual domain. Is there a way to quickly get Chrome to delete that expectation for my subdomains? Or is there a way to change SendGrid settings so that I eliminate the CNAME record and my subdomain redirects to the SendGrid domain? Perhaps something else.By the way, my subdomain has its own SSL certificate.I'm willing to switch to a different domain for my link tracking if necessary, but then I'll need a way to rewrite the links in old customer emails.
Fix broken link tracking due to HSTS on subdomain?
You can use phpsauto_prepend_fileandauto_append_filedirectives.It works like loading every script on your server viarequire_once()right between the files specified byauto_prepend_file(Loaded before your script) andauto_append_file(Loaded right after your script).To activate in.htaccess:php_value auto_prepend_file "/path/to/file/before.php" php_value auto_append_file "/path/to/file/after.php"Or inphp.ini(required when running in cgi-mode, affects wole webserver):auto_prepend_file = "/path/to/file/before.php" auto_append_file = "/path/to/file/after.php"before.phptry {after.php} catch(Exception $e) { ... }
So I was reading Twitter a bit until I saw this tweet by@DivineOmega:The perfect PHP error handler (pretty much), I coded it and I wanted to use it server-wide, butHow can I apply this file to all my PHP scripts?
Can I prepend a PHP file using .htaccess?
NameVirtualHost *:80 <VirtualHost *:80> ServerName example.com RedirectMatch 301 ^/$ /h </VirtualHost>This will help you to redirect all your request fromexample.comtoexample.com/h
I was just wondering how to perform a redirect from root in Apache.I want to check if someone goes to the root url (eg.example.com) and redirect them toexample.com/hautomatically.Can I do this in apache config, or in a.htaccessfile?
Apache redirect from root
When you use relative url's, the browser will dynamically create a complete url by using the url of the resource it loaded. In other words: It uses the url as it is displayed in the address bar. In your case (www.domain.com/subfolder/index.php/key) it tries to load any relative url relative towww.domain.com/subfolder/index.php/. Your resources are however not located there.You have two options to resolve this problem:Convert your relative url's into absolute url's, at least absolute to the domain root. Something like<img src="img/unicorn.png">should be turned into<img src="/path/to/img/unicorn.png">.Add a base to your head element. This base will be used instead of the url of the resource to calculate the complete url. You should add<base href="/">to your<head>element./will then be used as the base of any relative url.
I am trying to rewrite the URL through the htaccess file so that the following URLwww.domain.com/subfolder/index.php?keycan be accessed by:www.domain.com/subfolder/index.php/keythe specified "key" will determine which page to include in the PHP code. I have the following htaccess code already, however the CSS, JS, images and such are not being displayed when using the second (clean) URL. Any ideas as to what could be the issue?RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteCond %{DOCUMENT_ROOT}/$1 -f RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ /$1 [L,R=301,NC] RewriteRule ^index.php/([a-zA-Z0-9/_]+)$ index.php?key=$1
CSS, JS and images do not display with pretty url
In the apache config for the site, you have to extend AllowOverride properties. Add: FileInfo and AuthConfig. Or set "AllowOverride All"I had same problem, fixed with this config :<Directory /websites/mywebsite/> Options +FollowSymLinks +SymLinksIfOwnerMatch AllowOverride FileInfo AuthConfig </Directory>
I have a directory structure like the following for a website on Ubuntu 14.04, running apache 2.4.7:/websites/mywebsite/index.htm /websites/mywebsite/private.htm /websites/myqwbsite/folder/privatefile.ext /websites/mywebsite/folder/subfolder/publicfile.extIn the Apache config for the site, I have<Directory /websites/mywebsite/> AllowOverride Limit Require all granted </Directory>I want to use .htaccess files in the site folder such that the private.htm and privatefile.ext files areRequire all deniedbut everything else is granted.I tried the following two .htaccess files:/websites/mywebsite/.htaccess:<FilesMatch (private.*.htm)$> Require all denied </FilesMatch>/websites/mywebsite/folder/.htaccess:Require all denied/websites/mywebsite/folder/subfolder/.htaccess:Require all grantedHowever, apache gives a 500 - "Require not allowed here" for/websites/mywebsite/.htaccessHow can I make what I want happen with apache 2.4-compatible configuration (ie I do not want to load mod_access_compat and use the old style config)?
How to use Require directive to limit file access in apache 2.4
You can't route a request tooutsideof the site's document root, which is/var/www/thesite/web. So you can't access/var/www/thesite/or/var/www/thesite/apifrom inside the/var/www/thesite/webdirectory. The 400 Bad request is because of the../api/bit of your rule's target.Something you can try doing is just using php to include/require the api's index.php:RewriteRule ^api/(.*)$ /index_api.php [L]And in theindex_api.phpyou can include or require the "../api/web/index.php" file.
I have a website hosted in/var/www/thesite(apache server), it's aSymfony2website so inside this folder I have awebfolder to which my virtual host is pointing.So my virtualhost iswww.mysite.com -> /var/www/thesite/webIn this web folder I have a.htaccessto format URL nicely.Now, I've added an API in/var/www/thesite/api, the API is implemented usingSilex. I want to redirect all requesthttp://www.mysite.com/apito this new framework.So I've added in/var/www/thesite/web/.htaccessRewriteCond %{REQUEST_URI} ^/api RewriteRule ^api(.*)$ ../api/web/index.php [NC,QSA,L]But I get:Bad RequestYour browser sent a request that this server could not understand.I'm not sure if I can access parent folder in the.htaccess. I don't want to change my virtualhost target directory to avoid security breach.How can I solve this issue?
htaccess redirect URI to parent directory
The server probably hasn't setAllowOverride Indexes. If they haven't thenDirectoryIndexin an .htaccess file isn't allowed, and you get 500 when you try.Some options:See if the web provider will grantAllowOverride Indexesin your URL space.Ask what values of DirectoryIndex they do allow (maybe index.php, index.cgi, etc.) and use one of those instead.Use a RewriteRule (if they allow that :| ), for example:RewriteRule ^$ index.php
I have two index files and i want both to be there. I wroteDirectoryIndex index.php index.htmlin my.htaccessfile. This is the only line in my .htaccess file and when i opened site browser is giving error 500.
DirectoryIndex in .htaccess giving internal server error
It looks like it was because chrome was looking for favicon.ico (which caused a 404) and my .htaccess file points all 404s to index.php file which executed the code again.
Ok so I have a weird problem. I have a local XAMPP running and running Acrylic DNS Proxy as well. While I was testing some code I noticed that it was running the script twice. Here's what I got.index.php<?php $myFile = "test.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "1\n"; fwrite($fh, $stringData); fclose($fh); ?>.htaccess<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>AcrylicHosts.txt127.0.0.1 test.com 127.0.0.1 *.test.comVhost File<VirtualHost *:80> DocumentRoot /www/test ServerName test.com ServerAlias *.test.com </VirtualHost> <VirtualHost *:443> DocumentRoot /www/test ServerName test.com ServerAlias *.test.com SSLEngine On SSLOptions +StrictRequire SSLEngine on SSLCertificateFile conf/ssl.crt/server.crt SSLCertificateKeyFile conf/ssl.key/server.key SSLProtocol TLSv1 </VirtualHost>If you go totest.com, the text.txt output is "1\n 1\n"But if you go towww.test.com, the text.txt output is "1\n"Anyone know what to do to get it to stop running twice?Edit:These are the versions I'm working with:Apache 2.4.4 MySQL 5.5.32 PHP 5.4.19
PHP Script Running Twice
Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !^/(fingertools|static)(/|$) RewriteRule ^(.*)$ fingertools/$1 [L,QSA]
I have a server running with the following directory structure:/public_html | - /fingertools | - /css | - /static | - /media | - /js | - .htaccessMy .htaccess is in the root of the "public_html" folder, and the main files of the website are in the "fingertools" folder, which is a Django project.I want to rewrite through the .htaccess all requests tohttp://mydomain.com/to the "fingertools" folder, except any file insidehttp://mydomain.com/static/should be redirected to the "static" folder.I'm not able to do this, I need it to put all the CSS and JavaScript into this folder for the website to work.I have this so far:Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !(fingertools) RewriteRule ^(.*)$ fingertools/$1 [L]Which redirects me to my Django project, giving me a 404 error for not having the /static/ URL mapped in the urls.py file. Any ideas? Thank you very much
.htaccess redirecting all URLs except one
Yes it will affect the load time. The more rules/exceptions you have, the longer it takes to render. But: we are talking about micro/milliseconds that won't be even noticed by the human eye.
I am planing to add at most 10 .htaccess rewrite url codes in home directory will it affect execution ( loading time of site ) of my website ?my current .htaccess file isOptions +FollowSymLinks RewriteEngine On RewriteRule ^([0-9]+)/([0-9]+)/([^.]+).html index.php?perma=$3 RewriteRule ^movies/([^.]+).html gallery.php?movie=$1 RewriteRule ^album/([^.]+).html gallery.php?album=$1 RewriteRule ^img/([^.]+)/([^.]+).html gallery.php?img=$2 RewriteRule ^movies.html gallery.php
Will RewriteRules In .htaccess Affect Site's Speed?
Try this, which used e.g. in WordPressRewriteRule . index.php [L]or this, which is used by e.g. Lavavel PHP FrameworkRewriteRule ^(.*)$ index.php/$1 [L]You might also consider addingRewriteCond %{REQUEST_FILENAME} !-dbefore the RewriteRule to also exclude existing directories, not only existing files. But that's up to you.
i'm trying to remove index.php form an URL:this workshttp://server/bw/index.php/testthis doesn't workhttp://server/bw/testi try to change .htaccess and watching on web i see that it should be like this:RewriteEngine On RewriteBase /bw/ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [QSA,L]i try editing it in this way:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [QSA,L]or in this way:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ /bw/index.php [QSA,L]or in this way:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L] RewriteCond %{REQUEST_FILENAME} !-dBut when i try to access tohttp://server/bw/testit says me:Not Found The requested URL /bw/test was not found on this server. Apache/2.2.15 (CentOS) Server at server Port 80I check that inside myhttpd.confLoadModule rewrite_module modules/mod_rewrite.sois enable.. i don't know what to do now..how can i solve? please help me!
How to remove index.php from slim framework URL
I figured this out, thanks to my conversation Ansari and some help with the hosting company. The problem seems to be that the the url was being rewritten to index.php, and then it was being redirected again after that. So:RewriteCond %{REQUEST_URI} !^/services/xmlrpc RewriteCond %{REQUEST_URI} !index\.php$ [NC] RewriteRule ^(.*)$ http://www.wikiweightscore.com/$1 [L,R=301] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !=/favicon.ico RewriteRule ^(.*)$ index.php?q=$1 [QSA]This works for the exact use case I was wanting.
I need to redirect everything on one site to a new domain, except one path.So domain.com/anything needs to go to newdomain.com/anything.But I don't want domain.com/services/xml to redirect.I've tried lots of conditions, but nothing works. It always ends up redirecting it, or redirecting it to some other weird path on the new domain.This does not work:RewriteCond %{REQUEST_URI} !^/services/xml$ RewriteRule ^(.*)$ http://www.newdomain.com/$1 [L,R=301]Any help is appreciated. Thanks.
How to Redirect All urls to a new domain in apache, except one
use this:RewriteEngine On # mydomain.com/MyFolder/parameter-1 RewriteRule ^([a-z0-9\-]+)/?$ index.php?c=$1 [NC,L] # mydomain.com/MyFolder/parameter-1/parameter-2 RewriteRule ^([a-z0-9\-]+)/([a-z0-9\-]+)/?$ index.php?c=$1&d=$2 [NC,L]
mydomain.com/MyFolder/parameter-1I have this htaccess RewriteRule -RewriteRule ^([a-z0-9\-]+)/?$ index.php?c=$1 [NC,L]The .htaccess file is insideMyFolderand this only accept a single parameter.How can do a RewriteRule to accept 2 parametersmydomain.com/MyFolder/parameter-1/parameter-2Thanks
RewriteRule to accept 2 parameters
You have several possible solutions here:Reconfigure apache to use xxxx as document rootSetup a redirect in your main directory to the subdirectory, i.e. via a.htaccessrewrite rule or by sending a redirectionheader()in the rootindex.phpfile.
i create a site in a wampserver by creating a folder that include all site pages and namedthe folder for example xxxxwhen i runhttp://localhostits open the index of the wamp serverwhat i want is to open the index of xxxx when i run the localhoust without adding xxxxin the path likehttp://localhost/xxxxso is that possible
Redirecting index page in wampserver
You can useSetEnvIf, here's a snippet fromthis postby Tom Schlick.#allows a single uri through the .htaccess password protection SetEnvIf Request_URI "/testing_uri$" test_uri #allows everything if its on a certain host SetEnvIf HOST "^testing.yoursite.com" testing_url SetEnvIf HOST "^yoursite.com" live_url Order Deny,Allow AuthName "Restricted Area" AuthType Basic AuthUserFile /path/to/your/.htpasswd AuthGroupFile / Require valid-user #Allow valid-user Deny from all Allow from env=test_uri Allow from env=testing_url Allow from env=live_url Satisfy any
I am using a wildcard dns system that routes all subdomains through a single web app and sets a userid based on the first part of the URL (X.domain.com where X is the username).I now want to edit my htaccess file to enable conditional httpauth using htpasswd for specific domains. e.g. if url = password.domain.com the enable httpauth.I'm sure this is possible but have limited knowledge of htaccess.
Domain specific htpasswd conditions
Why do you have several .htaccess files? Where are the one's redirecting to public/$1 stored? You may very well be facing overriding RewriteRule directives that complicate things for you.Without knowing your setup it's fairly hard to say how you should be using rewrites - can you specify what things are ACTUALLY looking like?
I'd like to work with pages without trailing slashes. So now I want my URL's with an trailing slash to redirect (using .htaccess) to the same URL without the trailing slash.I got two .htaccess files:<IfModule mod_rewrite.c> RewriteEngine On RewriteRule (.*) public/$1 </IfModule>And one in my public folder:DirectoryIndex index.html index.php Options -Indexes <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?url=$1 [PT,L] </IfModule>I tried adding the following rule to the .htaccess file in the public folder:RewriteRule (.*)/$ $1 [R,L]But then: example.com/public/page/view/2/Redirects to: example.com/**D:/webserver/**public/page/view/2Which is obviously not what I want...
Remove trailing slashes
It's much better to have the multiple 301s. You don't want your customers to see a 404.There's no SEO penalty (that I'm aware of) for having multiple pages 301 to the same page.
We have updated our site recently; the old one had around 300 pages... the new one about 80 ;)This because in the old structure we had, for every argument, many pages. Instead, now we have just one page with a 'summary'.For example, the old structure about the 'car' argument was:Main page, 'cars'sub-page, 'tires'sub-page, 'engines'sub pages, 'accessories'etc...Now, we have just 1 page 'cars', with all inside.Actually, I redirect all the sub-pages to the main one, with .htaccess 301 redirect:Redirect 301 /cars-tires.php http://www.example.com/cars.php Redirect 301 /cars-engines.php http://www.example.com/cars.php Redirect 301 /cars-accessories.php http://www.example.com/cars.phpSo we have many different (even if the main topic is the same) pages pointing on one page.Do you think this is good for seo, or will be better redirect just the old main page and give a 404 not found to the old sub-pages?
Multiple 301 Redirects after restyling a website (SEO)
Here's a snippet to force everything to end with a slashrewritecond %{REQUEST_FILENAME} !-f rewritecond %{REQUEST_URI} !(.*)/$ rewriterule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]
This is a multi-site problem. I have a lot of sites with .htaccess files with multiple line similar to:rewriterule ^(page-one|page-two|page-three)/?$ /index.php?page=$1 [L]This means that both www.domain.com/page-one and www.domain.com/page-one/ will both load www.domain.com/index.php?page=page-oneHowever I'm always told that it is good SEO practice to make sure you use only one URL per page so what I'd like to do make www.domain.com/page-one to redirect to www.domain.com/page-one/ via the .htaccess file.Please note the answer I'mNOTlooking for is to remove the ?$ from the end of the line as that will just cause www.domain.com/page-one to become a 404 link.
How can I force some pages to end in a slash [.htaccess]
+25@Starkeen was right up to here :SetEnvIf host ^(env-uat\.com|host2\.com)$ NOINDEXFOLLOWSo , you could include the domains that you want to be involved in this Env like this :SetEnvIf host ^(env-uat|env-pre)\.com NOINDEXFOLLOWThen you should attach the Env with same name like this :Header set X-Robots-Tag "noindex, follow" env=NOINDEXFOLLOWNot like this :Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOWThe line above will look to Env its name is REDIRECT_NOINDEXFOLLOW not NOINDEXFOLLOW and it is diffrent case from this questionX Robots Tag noindex specific pageThat was about matching against Request_URI and for special case .So , the code should look like this :SetEnvIf host ^(env-uat|env-pre)\.com NOINDEXFOLLOW Header set X-Robots-Tag "noindex, follow" env=NOINDEXFOLLOW
I have three environments:env.com env-uat.com env-pre.comAll three pages run the same code. I want env-uat.com and env-pre.com to both get this in the htaccess:Header set X-Robots-Tag "noindex, nofollow"This will effectively completely unindex these pages, including PDF files etc. But I don't want to affect env.com.How can I make the Header X-Robots-Tag only be added for env-uat.com and env-pre.com and NOT env.com?** UPDATE **From what I could find so far, it would seem you can only do something likethis:SetEnvIf Request_URI "^/privacy-policy" NOINDEXFOLLOW Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOWBut this makes it specific to a PAGE. I want it specific to a DOMAIN.
htaccess header for specific domain?
As @Anubhava said, Directory dirctive is not allowed in htaccess contex ,this directive is available for use only in Directory context. You can use a RewriteRule to deny access to all except /dist directory :RewriteEngine on RewriteRule !dist - [F]This will forbid all incomming requests except a request for /dist.
I want to only provide public access to a single directory (/dist). I have an .htaccess file with the following:Order deny,allow Deny from all <Directory /dist> Order Allow,Deny Allow from all </Directory>I'm trying to first deny access to all, then overwirte that directive with a allow rule for the /dist directory. However, when I try to access any file through the browser, I get the following:Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at[email protected]to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log.What am I doing wrong?
Grant access to only one directory with .htaccess
.htaccess files - What they are/How to use themexplains how.htaccessfiles workA file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.This means, you can create a .htaccess file in/home/abc/public_html/, and another one in/home/abc/public_html/exclude/containing the same, different, or even contradicting directives.Looking atPHP -auto_prepend_file, you can see thatThe special valuenonedisables auto-prepending.The same applies toauto_append_file.Putting these two things together means, you can have the existing .htaccess# /home/abc/public_html/.htaccess <FilesMatch ".(htm|html|php)$"> php_value auto_prepend_file "/home/abc/public_html/_prepend.php" php_value auto_append_file "/home/abc/public_html/_append.php" </FilesMatch>and a second .htaccess in theexcludesubdirectory# /home/abc/public_html/exclude/.htaccess <FilesMatch ".(htm|html|php)$"> php_value auto_prepend_file none php_value auto_append_file none </FilesMatch>
I have the following .htaccess directive:<FilesMatch ".(htm|html|php)$"> php_value auto_prepend_file "/home/abc/public_html/_prepend.php" php_value auto_append_file "/home/abc/public_html/_append.php" </FilesMatch>I need to exclude a very specific directory '/home/abc/public_html/exclude/` from the auto_prepend and auto_append.Is it possible?
How to exclude a directory from FilesMatch
Your rules is usingANDoperation between 2 conditions but youOR.You can use this rule for enforcing bothwwwandhttps:RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]Make sure to clear your browser cache before testing.EDIT:As per comments below just forhttps://example.com to https://www.example.comredirect you can use this rule:RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
When I visit my site athttps://example.com, my browser responds with ERR_CONNECTION_REFUSED. Note that the following all work:https://www.example.comhttp://example.comredirects tohttps://www.example.comhttp://www.example.comredirects tohttps://www.example.comHow can I redirecthttps://example.comrequests tohttps://www.example.comusing .htaccess?I've tried the following which doesn't seem to work:// .htaccess RewriteEngine On RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
How to redirect HTTPS non-www to HTTPS www using .htaccess?
Have this rule in/myapp/.htaccess:RewriteEngine On RewriteBase /myapp/ # If the request is not for a valid directory RewriteCond %{REQUEST_FILENAME} !-d # If the request is not for a valid file RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.+) index.php/$1 [L]
Actually I need to add index.php in my application URL through htaccess file.My URL is like this.http://localhost:8080/myapp/xyz/abs.htmlI need to change this into.http://localhost:8080/myapp/index.php/xyz/abs.htmlCan anyone tell me what i need to be write in htaccess file.Any Help will be appreciating.Thanks.
how to add index.php in the URL through htaccess
EachRewriteCondcondition only applies to the immediately followingRewriteRule. That means if you have a bunch of rules, you have to duplicate the conditions. If youreallydon't want to do that for some reason, you could use a negate at the very beginning of all your rules. This may or may not be a good solution since it could affect how you make future changes to the rules:RewriteEngine On RewriteCond %{HTTP_HOST} !^(www.)?example.com RewriteRule ^ - [L] RewriteRule ^some_action1/?$ index.php?some_action1 [L] RewriteRule ^some_action2/?$ index.php?some_action2 [L] RewriteRule ^some_action3/?$ index.php?some_action3 [L] etc...So the first rule checks for the negative of the host being example.com, and skips everything. Then you can add all your rules without having to worry about that condition.However, if your "some_action" is always going to be part of the GET parameters, you can maybe just use a single rule:RewriteEngine On RewriteCond %{HTTP_HOST} ^(www.)?example.com RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/?$ index.php?$1 [L]
On the side I have about 400,000 subdomains. in view of the above, some calls also operate subdomain level, e.g..subdomain1.example.com/some_action/Such actions that should be performed only from the domain have 27.Htaccess file I created a rule:RewriteEngine On RewriteCond %{HTTP_HOST} ^(www.)?example.com RewriteRule ^some_action1/?$ index.php?some_action1 [L]If i add this lineRewriteRule ^some_action2/?$ index.php?some_action2 [L]not work in the same way as for some_action3, etc.I have added for each action separatelyRewriteCond %{HTTP_HOST} ^(www.)?example.comCan you somehow skip to harmonize?
Multiple RewriteRule to one RewriteCond
I figured out a major fix for getting Google Fonts to work in Firefox.This fix involves adding an @font-face to your stylesheet.Oddly enough it was by accident, while I was in firefox.In Firefox, go to Google.com/fonts and find your font in the list.Assuming it has rendered correctly, highlight a portion of the text, right click and Inspect Element.If your inspect element is side mounted, on the bottom labels, and if it is bottom mounted, on the right side labels, select "Fonts" next to rules/computed.You should now be able to see CSS code related to your chosen font. It uses DIFFERENT links than what Google gives to you in their stylesheets.For your PT Sans, this should work.@font-face { font-family: "PT Sans"; font-style: normal; font-weight: 400; src: local("PT Sans"), local("PTSans-Regular"), url("http://fonts.gstatic.com/l/font?kit=fQl5KuJ0t7CxaofpRWHFZ5uy9QftGgiCbPT5J2Tle6QGEtCW0q5T6QHEAICoCh1h9R715REvNVFz5maQ3RAjMvuvYlUZxjWJuWoIFYd8ZVs9VGRJmXaKNSd0UG6XHo4E") format("woff2"), url("http://fonts.gstatic.com/l/font?kit=9HC7E4PH-EC-60ASiiwijJuy9QftGgiCbPT5J2Tle6QGEtCW0q5T6QHEAICoCh1h9R715REvNVFz5maQ3RAjMvuvYlUZxjWJuWoIFYd8ZVs9VGRJmXaKNSd0UG6XHo4E") format("woff"); }Also, when you use apply the font family, do it this wayfont-family: 'PT Sans', sans-serif !important;That has worked for every font for me so far.I know I'm a bit late but if you still don't have a fix I hope this helps.
I really can't use the Google Fonts in Firefox. Basically i have one font from Google Fonts, it works fine in other browsers, but, in the firefox, the font doesn't work.My Source:HEAD:<link href="http://fonts.googleapis.com/css?family=PT+Sans:400,700" rel="stylesheet" type="text/css" />And, i have tried to put that .htaccess file, but it doesn't work:.htaccess:# BEGIN REQUIRED FOR WEBFONTS AddType font/ttf .ttf AddType font/eot .eot AddType font/otf .otf AddType font/woff .woff <FilesMatch "\.(ttf|otf|eot|woff)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch> # END REQUIRED FOR WEBFONTSAnybody saves me?
Google Fonts don't work in Firefox
jQuery supports the error event for images — I'm not sure why your inline example isn't working, but how about:$('img').on('error', function() { $(this).attr('src', 'default.jpg'); });This also has the advantage of not needing to be added to each element. Your .htaccess solution doesn't work if your images are being hotlinked, since those would not be served from your site.
On a daily basis I automatically imported several XML-feeds (Tradetracker, Daisycon, etc.) for an affiliate site using PHP. The feeds contain products from all kinds of shops.Everything works like a charm, with exception of the images. The images in the feeds are simply hotlinked to an image of the provider. This works in most of the cases, however sometimes (due to various reasons) the image doesn't exist anymore, is hotlink protected, is changed, etc. etc. This results in "image not found" in the browser, which doesn't look good.I tried to solve this using htaccess, but for whatever reason, it doesn't work. I googled and tried several htacces "scripts", but none without success. I also tried JS in the image URL but this didn't work eiter. I do prefer htaccess.Anyone has a suggestion?Replace image using htaccessRewriteEngine on <FilesMatch ".(jpg|png|gif)$"> ErrorDocument 404 "/noimage.jpg" </FilesMatch>Using JS<img src="image.jpg" onerror="this.onerror=null;this.src='default.jpg'">Update: Working Version<script type="text/javascript"> jQuery(window).load(function() { jQuery("img").each(function(){ var image = jQuery(this); if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){ jQuery(image).unbind("error").attr( "src", "noimage.jpg" ); } }); }); </script>
Fallback for 404 images
What you are looking for is Apache Url Rewriting.I will break it down a bit for you to help you understand, it helps to know a bit ofregex.there are a lot of answers here that discuss the method, but to sum it all up, you need to do three things.# Switch on URL Rewriting # Choose the URL that you want to display # Point it to the true URL that gives the information. Options FollowSymLinks RewriteEngine On RewriteRule ^all-products/items-on-sale/health/adaaos45/?$ all-products/?onsale=true&topic=health&item=adaaos45 [NC,L]Now of course, if you would want to match any results for the variables, you need to match the word in regex, and remember it, and use it in the last part of the line. But this should get you started on understanding what is going on.With this code in your .htaccess, browsing tohttp://www.example.com/all-products/items-on-sale/health/adaaos45will show you the content that displays on this page.http://www.example.com/all-products/?onsale=true&topic=health&item=adaaos45
I am a bit new to this but I am trying to learn. I know that in PHP we can have a URL that ends in?id=somethingbut it seems to me that some websites are doing it just forward slashes. Is this possible using PHP? I sawthesequestionsthat seem to say it is possible but I haven't cracked it yet.Can someone prompt me in the right direction formod_rewrite? I would like to change the following URLhttp://www.example.com/all-products/?onsale=true&topic=health&item=adaaos45intohttp://www.example.com/all-products/items-on-sale/health/adaaos45Can you point me into the right way?
Can someone prompt me in the right direction to use mod_rewrite?
TheRewriteBasein the codeigniter directory should say/codeigniter/RewriteBase /codeigniterOtherwise the rewrite toindex.phpends up going to wordpress' router.
I'm having some issues with a Codeigniter app in a subfolder on my server along with a Wordpress install in the document root. If I hide theindex.phpof the Codeigniter URL with.htaccess/codeigniter/.htaccessDirectoryIndex index.php <IfModule mod_rewrite.c> RewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|user_guide|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 404 index.php </IfModule>And get Wordpress to ignore/codeigniterwithRewriteCond %{REQUEST_URI} !^/(codeigniter).*$/.htaccess# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_URI} !^/(codeigniter).*$ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>Then navigate towww.mysite.com/codeigniter/my_controller/my_function, I get a 404 errorNo input file specified.I foundhere, that adding a?afterRewriteRule ^(.*)$ index.phpsolves the Codeiginiter 404 error./codeigniter/.htaccessRewriteRule ^(.*)$ index.php?/$1 [L,QSA]However I'm now getting a Wordpress 404 error, so it seems if I replaceindex.phpwithindex.php?in/codeigniter/.htaccess, the Wordpress rewrite rule in/.htaccess,RewriteCond %{REQUEST_URI} !^/(codeigniter).*$gets ignored. Is there a better way to handle this?Thanks in advance!
Remove index.php from Codeigniter URL in subfolder with Wordpress in root
You don't use htaccess to do this, you use your app to remove the extensions, and htaccess to map extension-less urls to real files. This rule# Remove file extension RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*) $1.php [L]Says, "if the requested resource doesn't exist as a file, look for the resource with a.phpextension". So you remove the extension from all links in your app, and this rule will make the php file run without the extension. Your htaccess is fine as-is, you need to update your app.
I just finished installing a LAMP stack on Ubuntu 12, and have run into an issue with Apache's .htaccess file. I have the rewrite and redirect mods enabled, and the .htaccess file is working (the URI will redirect to 'www' if there is no 'www' present), but no matter what I try, I cannot get it to remove file extensions. I've tried the<Files>directive with no luck. My current file consists of the following:RewriteEngine On # Remove file extension RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*)$ $1.php [L] # Force www RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]Any suggestions on how to fix this very annoying problem?
Using .htaccess to remove PHP file extension from URL
+50If adding the settings into your .htaccess file that Sergio mentioned isn't working, you may have to go straight to your VirtualHost entry. and add the rules. I'll let the more experienced apache folks here chime in, but that's where I would go.
In a web folder, I currently cannot access.txtfiles via URL in browser. How can I modify myhtaccessfile, so that files with type.txtcan be accessed via URL in browser?
htaccess allow .txt files
You can create a .htaccess file in your localhost. Simply make sure it is in the root directory of your web server (I believe in WAMP, it's the www folder). In XAMPP, it's the htdocs folder
I want to create a personalized404 error pagein php , I want to it works in localhost, as you know the localhost does not have .htaccess file !
create a personalized 404 error page in php in localhost
Use this rule :RewriteEngine on RewriteRule ^images/(.*)$ http://images.domain.com/$1 [L,R=301]
I'm struggling with an .htaccess rewrite, can anyone point me in the right direction please?I want to be able to rewrite all requests towww.domain.com/images to images.domain.com (the subdomain is on a different server), keeping any filename and sub-folder requests intact.So requests to www.domain.com/images/folder1/image1.jpg will get the image from images.domain.com/folder1/image1.jpgThanks.
Rewrite a directory to domain
You can use mod_rewrite'sEflag:RewriteRule ^ - [E=ENV:VALUE]Which will guarantee that it gets set before (or after) rules get applied.
If I want to set an environment variable before RewriteRules are evaluated,I have to useSetEnvIfinstead ofSetEnv. However,SetEnvIfrequires one to have a condition. As it is, I have:SetEnvIf Request_Method ^ ENV=VALUEIs there a better way to do this?
htaccess SetEnvIf true
I used deflate mode in this way:<IfModule mod_deflate.c> # Compress HTML, CSS, JavaScript, Text, XML and fonts AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/xml </IfModule>And it's working perfectly for me. Pagespeed for my site is: Desktop: 91 Mobile: 83References which I have used for my site:http://www.quickregisterseo.com/improve-google-page-speed-score-wordpress-without-plugins/https://dzone.com/articles/steps-improve-your-pagespeed-insight-score
i have a linode sever with centos 6 , as it wont support mod_gzip, i am using mod_deflate.this is my code in .htacess<IfModule mod_deflate.c> <FilesMatch "\\.(js|css|html|htm|php|xml)$"> SetOutputFilter DEFLATE </FilesMatch> </IfModule>when i tested usinghttp://www.whatsmyip.org/http-compression-test/, its saying 'my site is gzipped' , but when i used pagespeed in chrome, it still suggest 'Enable compression'whats wrong? any problem with my .htaccess code?
mod_deflate in .htaccess and google pagespeed
+50How about something like this?RewriteEngine on RewriteRule ^static/([^/]+\.(png|jpg|css|js))x?/\d{8,15}$ /static/$1 [NC,L] <FilesMatch "\.(png|jpg|css|js)$"> <IfModule mod_expires.c> ExpiresActive On </IfModule> <IfModule mod_headers.c> ExpiresDefault "access plus 10 years" </IfModule> </FilesMatch>
Hey there!I have a folder/staticin my Apache 2.x server webroot. If a request matches/static/<somename like [\S-_]+>.(png|jpg|css|js)/\d{8,15}for example/static/bg.jpg/1335455634I want two things:url shall be rewritten to/static/bg.jpg(getting rid of the timestamp)it shall become anever-expire('expires 2030, max-age=290304000, public cache, ...)If the request does not match, the request and it's headers should be as normal, no rewrite. Ideally, any request outside /static/* should not be affected (though «coincidental trailing timetamps» should be rare...)I have nothing but trouble with FilesMatch / RewriteCond, so I rather not post my poor attempts... (Rewrite in genereal is enabled on my machine, and I do possess the rights to send cache-related headers)Dankeschön!
htaccess - conditional rewrite and expire
You can use the following syntax to make an exception:RewriteRule name_of_page_to_exclude.php - [L]The dash (-) is important. The[L]makes sure that if this rule is triggered, it's the last one that will be processed. So naturally, you'll need to place it near the top of your.htaccessfile, before the rule in your question:RewriteEngine on RewriteRule name_of_page_to_exclude.php - [L] RewriteRule (.*) controller.php [L]Thedocumentationhas the following to say:- (dash) A dash indicates that no substitution should be performed (the existing path is passed through untouched).
I am creating php front controller. this is my.htaccessfile.<IfModule mod_rewrite.c> RewriteEngine on RewriteRule (.*) controller.php [L] </IfModule>This code redirect all url to thecontroller.php. I need to avoid redirectindex.phpto thecontroller.php. All other urls should redirect to thecontroller.php.
How to prevent one file from .htaccess redirect?
RewriteRule ^([a-zA-Z0-9-/]+)/([0-9]+)$ index.php?slug=$1&customId=$2 [QSA]
I'm using the following line in my .htaccess file to create custom page stubsRewriteRule ^([a-zA-Z0-9-/]+)$ index.php?slug=$1 [QSA]So basically this turnsmy-site.com/my-fancy-urlintomy-site.com/index.php?slug=my-fancy-siteI need to add an additional variable onto the query string like this:my-site.com/index.php?slug=my-fancy-site&customId=5So I can use this URL:my-site.com/my-fancy-url/5Any ideas how I would alter the Rewrite rule to achieve this?
Custom Page Slug with multiple query strings using htaccess
You may want to perform something like this:RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/(.*)$ /htroot/$1/index.php?data=$2 [L]If the first wildcard match(.*)isaaaand the second wildcard match(.*)isxyz(htroot/aaa/xyz) it will get the content fromhtroot/aaa/index.php?data=xyzand you will be able to get the valuexyzin index.php with$_GET['data']
Is it possible to make .htaccess "understand" dynamic relative paths and redirect to them properly?My setup goes as follows:http://domain.com/htroot/aaa/xyz http://domain.com/htroot/bbb/xyz http://domain.com/htroot/ccc/xyzAnd so on. For the sake of the example, "htroot" contains the .htaccess I need to modify. The following sublevels (aaa, bbb, ccc) can be any a-z0-9 name, and the folders have an index.php (or any other .php to be redirected to). Thexyzshould work as a parameter of sorts, see next part. Thexyzpart is nowhere on the filesystem as a "physical" folder or file.What I need to achieve is the following: When you access with the urlhttp://domain.com/htroot/aaa/xyzit gets content fromhttp://domain.com/htroot/aaa/ (or http://domain.com/htroot/aaa/index.php, either way)where the index.php kicks in -> I can get thexyzparsed from REQUEST_URI and process it to serve the correct content that it specifies, while the URL of the page stays ashttp://domain.com/htroot/aaa/xyz, naturally.So far I have managed to pull this off if every sublevel (aaa etc.) has it's own .htaccess, but I would need one where there is only a single .htaccess located inhtrootthat handles this. I'm guessing it might have something to do with the $0 parameters in .htaccess, but not sure.
Redirect to dynamic relative paths with .htaccess?
You could just force a trailing slash with .htaccess Something global would look like this (quick untested code)RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ $1/ [L,R=301]You can ofcourse just specify the root, and not use the (.*).
I've got a problem with a website, and i don't know which code i must use to solve it.I've run a crawl test, which results in the following structure:www.domain.comwww.domain.com/ (this is abigproblem, because it's duplicate content)www.domain.com/categorywww.domain.com/category/pagewww.domain.com/category2www.domain.com/category2/pagewww.domain.com/category3/subcat4/pageetc.As you can see, the subpages don't have a trailing slash. My question is:What redirect code is the most effective way to solve the duplicate homepage problem?Taken in account, the subpages don't have (so don't need?) a trailing slash.
What redirect code can solve my duplicate homepage?
Simple The rules below force www, except for subdomains.RewriteCond %{HTTP_HOST} =name.domain [NC] RewriteRule ^(.*)$ http://www.name.domain/$1 [R=301,L]Edit and paste it, restart apache.Explain:RewriteCond %{HTTP_HOST} =name.domain [NC]match only when someone types name.domain (your domain name).When types subdomain.name.domain the RewriteCond is false and not redirect. You understand? In rule that you previously posted you was matching for !(not)^(beginning by)www and subdomain.name.domain satisfied RewriteCond and is what you don't want. :)
I want to force "www." on my URLs (e.g.http://domain.combecomeshttp://www.domain.com). However, I don't want it forced on URLs that already have a subdomain (e.g.http://images.domain.comshould NOT becomehttp://www.images.domain.com). The following snippet I found on the net does the latter:RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]What do I need to do to get this to work for me? Thanks.
Force "www." via .htaccess
Use<Files *>to match any file.If you want to match only files that do not have extensions, use<Files [^.]+>.
This is my .htaccess file:<Files .*> ForceType application/x-httpd-php SetHandler application/x-httpd-php </Files> <Files mytesting> ForceType application/x-httpd-php </Files> <Files *.asp> ForceType application/x-httpd-php </Files>Is it possible using the ForceType directive to allow extensionless files, rather than doing selected extensions, e.g. the mytesting one above?Thanks
.htaccess and ForceType question - extensionless files?
Working example, visit:http://www.jakeisonline.com/stackoverflow/3345518-mass-301-redirect/page.htmlYou should be redirected straight to /page.htmlOptions +FollowSymlinks RewriteEngine on RewriteRule ^(.*)page.html /page.html [R=301,NC]This will always redirecthttp://www.foo.com/something/something/something/page.htmlback tohttp://www.foo.com/page.htmlusing a 301 hard redirect.The rewrite rule does this by looking at the URL, determining if anything before page.html is included (excluding the domain itself) and if it is, will 301 redirect. So you can literally use any sub-level, and as long as it ends with page.html, it will redirect to /page.html in the root directory.In case you're wondering what[R=301,NC]means,R // means simple redirect R=301 // means redirect with a 301 header NC // means no-case, or case insensitive L // can also be used to say 'ignore all the other rules after this'
I am working on a large project that involves taking thousands (30,000+) static web pages and turning it into to a CMS.The issue is many of these pages are duplicates within their directories. I want to keep the SEO intact by using 301 redirects, however, I am not sure how to go about doing such a large redirect (301).Here is an example of the current directory structure for the pages./page.html /folder/page.html /folder/subfolder/page.html /folder/subfolder/anotherfolder/page.htmlAs you can seepage.htmlis duplicated in all the directories.For the new CMS the URL to that page would just be/page.html.
Mass 301 redirect using .htaccess
You can define rules in Apache's virtualhost config (one step above .htaccess, you'll have to ask an administrator to edit this):<VirtualHost *:80> ServerName piskvor.example.com ServerAlias *.host2.example.com php_value session.save_path /home/piskvor/tmp </VirtualHost> <VirtualHost *:80> ServerName someotherhost.example.org php_value session.save_path /tmp </VirtualHost>This gives you the possibility to configure each host differently (by hostname or a hostname wildcard). Most newer Apache setups support this.
for our project we need to set several PHP values depending on the environment (development/production), most notably session save path and some tracing and profiling settings.We do not want to set them in the PHP script because due to some horrible legacy code which would require a lot of changes and we don't want to have to change the .htaccess every time before commiting it to git (but we require the .htaccess to be in source control).Is there any way to do something like this in the .htaccess:if (hostname == "dev.example.com") { php_value session.save_path /tmp [...] }
.htaccess Set PHP Value depending on Hostname
If you addRewriteCond %{REQUEST_URI} !^/blog/.*$ RewriteCond %{REQUEST_URI} !^/utilities/.*$belowRewriteCond %{REQUEST_URI} !=/favicon.icoYou should be fine.
I have a drupal installation in the root directly of my domain with clean urls enabled. I also have a sub directory with wordpress installed. /blog/ I also have a sub directory with php scripts in it /utilities/When I type in "http://www.domain.com/blog/a-post/" I get a 404 error from Drupal telling me that the page does not exist. same goes with "http://www.domain.com/utilities/pig/"I know this has something to do with the ".htaccess" file. That was created when I turned on "clean urls" in Drupal.I'm looking for information on how to set up the .htaccess file or a code snippet that i could use to tell Drupal to ignore these two directories.
Drupal and wordpress on the same site
This can be accomplished using the cPanel GUI. Here are some instructions I found:Add Password ProtectionLog into cPanel.Go to the Files section and click on the Directory Privacy icon.Select the directory you want to password protect and then you will see Set permissions for $PATH screen appear.Click on the checkbox labeled "Password protect this directory:".Type a name for the folder you are trying to protect in the field labeled "Enter a name for the protected directory:".Click the Save button to save the name you have entered for the directory and option to password protect the directory.Create a user to grant access to the protected directory by typing the credentials into the Username, New Password and Confirm Password fields.Click Save in order to save the credentials that you have entered.SOURCE:https://www.inmotionhosting.com/support/website/protecting-files/how-do-i-password-protect-a-directory-in-my-control-panel-cpanelNOTE:The wording and location of these steps may change between cPanel versions. These instructions enable something called "HTTP BASIC" which is not considered secure. This QA can help explain why you shouldn't use this to protect sensitive data:https://security.stackexchange.com/questions/988/is-basic-auth-secure-if-done-over-https
I am working on a website in which I want to restrict the access to it by entering some username and password in it likeif I/or any outside users open the website, it should ask forUsernameandPassword.The current code which I am using in .htaccess file inside public_html folder is:<IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^(.*)$ public/$1 [L] </IfModule>Problem Statement:I am wondering what changes I should make in the.htaccesscode above so that it allows outside users to enter username and password to enter the website.
How can I restrict access to our website through .htaccess in cpanel?
This is likely to be a problem with your Apache version and the fact that PHP runs as FastCGI.In Apache 2.2.X there was a bug:https://bz.apache.org/bugzilla/show_bug.cgi?id=49308I found a couple of other posts that propose to use thealwayscondition to fix the problem:Header always add TestHeader "It works."Also see:https://serverfault.com/questions/152373/mod-headers-not-working-for-php-mod-fastcgi-pageshttps://serverfault.com/questions/383011/mod-headers-not-sending-headers-when-file-is-phpproblems using mod_headers with php-fpm/mod_fastcgiComments in:Apache won't set headers for PHP script
Is it possible to add headers (defined in a.htaccessfile) to a response generated by PHP?I have the following.htaccessfile in my that should add a HeaderTestHeaderto each response delivered by my Apache Webserver:#<IfModule mod_headers.c> # Header unset X-Powered-By Header add TestHeader "It works." #</IfModule>I also have three additional files in that folder:html.html<html>content</html>1.php<?php echo "<html>content php</html>";2.php<?php header("TestHeader: Sent from PHP."); echo "<html>content php</html>";Requestinghtml.htmlreturns the headerTestHeader: "It works."Requesting1.phpdoesnotreturn headerTestHeaderRequesting2.phpreturns the headerTestHeader: "Sent from PHP."Is it somehow possible to manipulate the response header from PHP output using.htaccessdirectives?EDIT: PHP runs asFastCGIon the server.
Manipulate Headers of PHP response in .htaccess-file?
RewriteRule ^productos.php /?view=productos [L,NE,B,QSA]or if you want to redirectRewriteRule ^productos.php /?view=productos [L,NE,B,QSA,R=301]
I'm trying to set a simple htaccess rule, but is not working.I think the problem is with the?and=characters?The code is:Options +FollowSymLinks ErrorDocument 404 /php/404redirect.php RewriteEngine on RewriteRule ^productos.php?id=([0-9]+)$ /?view=productos&id=$1 [L,NE,B,QSA]This always give me error 404.What I want is redirect all requests from:www.example.com/productos.php?id=Xtowww.example.com/?view=productos&id=X
Simple htaccess rewrite rule error 404
Try this :RewriteEngine on RewriteCond %{QUERY_STRING} ^page=([^&]+)&id=([^&]+)$ [NC] RewriteRule ^index\.php$ http://alois-seckar.cz/politics-%1/%2? [NC,L,R]Empty question mark at the end is important to discard the orignal query strings from the destination url.%n is part of the regex in RewriteCond, it's the part matched between ([ and ]+).This rule will redirectexample.com/index.php?page=foo&id=bartoexample2.com/politics-foo/bar
I have already checked a lot of answers related to .htaccess redirecting, but yet I was unable to elaborate my problem:I have an old website with blog entries addressed like this:http://ellrohir.mzf.cz/index.php?page=blog&id=77Now I also have a new website with "nice urls" where blog entries can be found using:http://alois-seckar.cz/politics-blog/77I want to "shut down" the old page and redirect any old links to new site. How to catch and transfer the old url to the new url? I still cannot figure the necessary .htaccess code up :(
.htaccess redirect using GET parameters
Try these directives at top of your .htaccess:Options -Indexes ErrorDocument 404 /Page-Not-Found.html ErrorDocument 403 /Page-Not-Found.html
I have used my.htaccessfile toProvide a 404 pageTurn off directory scanning.Here is the relevant portion of the.htaccessfile:Options -Indexes ErrorDocument 404 /Page-Not-Found.htmlThe 404 part works.Test.However, going to a directorythat actually exists(directory scanning) gives back this:Forbidden You don't have permission to access /chihuahuaStories/2014/ on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request
You can try this :RewriteRule ^test$ /test.php [L]place it above your generic redirection written for all site url.Like for example :RewriteRule ^test$ /test.php [L] --page wise condition RewriteRule ^/?$ "http\:\/\/example\.com\/" [R=301,L] -- generic for site RewriteRule ^(.[^\.]*)$ index.php?$1 [QSA,L] -- generic for site
Is there a possibility to redirect requests forexample.com/testtoexample.com/test.phpfor a particular file using.htaccess, leaving all other files/extensions intact?
.htaccess remove extension for a single file
The redirection occurs in theredirect_canonicalfunction. There is a filter applied to the redirect URL before the redirection occurs:$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );If you hook into that filter you should be able to disable the redirection.add_filter('redirect_canonical', function($redirect_url, $requested_url) { if($requested_url == home_url('index.php')) { return ''; } }, 10, 2);I verified that this is working by adding the above filter to my theme'sfunctions.phpfile. Note that this filter must be attached before the redirect action fires so placing the filter in a template file will not work.
I need to be able to browse tohttp://www.example.com/index.php, but WordPress automatically 301 redirects this tohttp://www.example.com/.Is it possible to stop this redirection ONLY for the homepage?Here is my .htaccess file:# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
Stop WordPress from 301 redirecting /index.php to /
You can use these 2 rules in your root .htaccess:RewriteEngine On RewriteBase / RewriteRule ^([^/]+)/([^/]+)/?$ $1-$2 [NE,L,R=302] RewriteRule ^([^/]+)/(.+)$ $1-$2This will redirectexample.com/foo/bar/baz/abc/xyz/123toexample.com/foo-bar-baz-abc-xyz-123
There are a fewsimilarquestionson SO, but none that work for this specific scenario.I want to replace all forward slashes in a URL path with dashes, usingmod_rewrite.Sohttps://stackoverflow.com/foo/bar/bazshould redirect tohttps://stackoverflow.com/foo-bar-baz.There could be any number of segments in the path (between forward slashes).I think the solution involves theN flag, but every attempt I've made results in an endless loop.
Replace all forward slashes with dashes
You can use this code in yourDOCUMENT_ROOT/.htaccessfile:RewriteEngine On RewriteBase / # external redirect from actual URL to pretty one RewriteCond %{THE_REQUEST} \s/+fr/transporter/transporterPublicProfile\.php\?profil=([^\s&]+) [NC] RewriteRule ^ fr/profil-des-transporteurs/%1? [R=302,L,NE] # internal forward from pretty URL to actual one RewriteRule ^fr/profil-des-transporteurs/([^/.]+)/?$ fr/transporter/transporterPublicProfile.php?profile=$1 [L,QSA,NC]Then for resolving relative links used for images/js/css paths you can add this in the<head>section of your page's HTML:<base href="/fr/transporter/" />
I want to rewrite my URLFrom:https://example.com/fr/transporter/transporterPublicProfile.php?profil=1927To:https://example.com/fr/profil-des-transporteurs/1927When ever a user visit this URL:https://example.com/fr/transporter/transporterPublicProfile.php?profil=1927It should appear like this:https://example.com/fr/profil-des-transporteurs/1927And if a user visit this URL:https://example.com/fr/profil-des-transporteurs/1927Its should remain as it is.What I have tried so far is:RewriteRule ^profil-des-transporteurs/(.*)$ /fr/transporter/profil.php?oid=$1 [L]It changes the URL as I want but the problem is that, the links on that page doesn't works properly. The page is using relative paths for images etc w.r.t new URL i.e:https://example.com/fr/profil-des-transporteurs/
URL rewriting without changing URL .htaccess
+300Firstly if you have root access .. you can check your php version ...php -vupgrade it to php 5.4 .i have installed Laravel in Directadmin successfully by using below .htaccess config file inside public folder ...<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes... RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]In direct admin you can change the apache config of Document root for specific domain insideetc/httpd/conf.d/domians/yourdomian.confchange it to ...DocumentRoot "/var/www/html/domians/yourdomain/public"Thats it ;) It should work fine ;)
I am trying to install Laravel on vps with Direct admin. Below is my Apache config file<VirtualHost MYIP:80 > ServerName www.domain.com ServerAlias www.domain.com domain.com ServerAdmin[email protected]DocumentRoot /home/mydir/domains/domain.com/public_html ScriptAlias /cgi-bin/ /home/mydir/domains/domain.com/public_html/cgi-bin/ UseCanonicalName OFF <IfModule !mod_ruid2.c> SuexecUserGroup mydir mydir </IfModule> CustomLog /var/log/httpd/domains/domain.com.bytes bytes CustomLog /var/log/httpd/domains/domain.com.log combined ErrorLog /var/log/httpd/domains/domain.com.error.log <Directory /home/mydir/domains/domain.com/public_html> php_admin_flag safe_mode OFF php_admin_flag engine ON php_admin_value sendmail_path '/usr/sbin/sendmail -t -i -f chat$ php_admin_value mail.log /home/mydir/.php/php-mail.log php_admin_value open_basedir /home/mydir/:/tmp:/var/tmp:/usr/loc$ </Directory> </VirtualHost>According to the Laravel manual I have to point to thepublicdirectory. After I setdoc rootto/home/mydir/domains/domain.com/public_html/publicI get this error when I try to accessdomain.com500 Internal Server ErrorUPDATE:/var/log/httpd/domains/domain.com.error.logcontains this Laravel errorPHP Parse error: syntax error, unexpected '[' in /home/mydir/domains/domain.com/public_html/vendor/laravel/framework/src/Illuminate/Support/helpers.php on line 411
Apache Configuration for laravel installation on directadmin
A better way to accomplish this would be to only rewrite if a.phpby that name exists. Otherwise throw404for the original URL. The second set of rules would take care of removing the extension and avoiding the redirect loop.Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php [L] RewriteCond %{THE_REQUEST} ^(?:GET|POST)\ /.*\.php\ HTTP.*$ [NC] RewriteRule ^(.*)\.php$ $1 [R=301,L]
I have a rewrite condition in my .htaccess file which removes the need for .php file extensionRewriteEngine On RewriteRule ^([^.]+)$ $1.phpsohttp://site.com/blogopenshttp://site.com/blog.phpbut if old users type /blog.php it will also load the pageis there a way to prevent or redirect pages with .php or any other file extention to the one without it?i mean if user entered /blog.php or /blog.asp it should either fail to load or redirect to /blog (without extention)
Prevent loading pages with .php file extension (only load without it)
RewriteBase /mysite RewriteCond %{QUERY_STRING} ^view=(registration)$ [NC] RewriteRule ^component/users/$ %1.html? [R=301,L]If you want it to work only forregistrationthen you can specify that instead a catchall regex.Also keep in mind that since you had it with a global permanent redirect you may need to clear your browser cache or use a different browser to instantly see the changes.
I already started a topic some weeks ago. But I got now a new problem that is very similar to the old problem:.htaccess rewrite URL with a question mark "?"My aim was this URL:/mysite/component/users/?view=registrationRewrite into this new URL:mysite/registration.htmlMy current.htaccessgot this code:RewriteBase /mysite RewriteCond %{QUERY_STRING} ^view=(.*)$ RewriteRule ^component/users/?$ %1.html? [R=301,L]It worked very fine.But then I noticed that this config concerns all URL that starts like this:/mysite/component/users/?view=For example this config would also concern an URL like this:/mysite/component/users/?view=remindThis is what I don't wantI only want this URL rewritten:localhost/mysite/component/users/?view=registration
.htaccess rewrite URL with a question mark “?” only for 1 specific URL
There are 2 steps:Rewrite the url using an.htaccessfile (on linux). You need to make sure all requests go to your php file so you will need to rewrite all requests to non-existing files and folders to your php file;In your php file you analyze the url (using for example$_SERVER['REQUEST_URI']) and take action depending on its contents.For step 1. you could use something like:RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ your_file.php?url=$1 [L,QSA]And then in your php file in step 2. you have the requested url in$_GET['url'].Edit:If you want to rewrite only certain sub-directories, you could also use a rule like:RewriteRule ^sub/dir/to/rewrite/(.*)$ your_file.php?url=$1 [L,QSA]Some details:^(.*)$captures everything (all characters) between the start^and the end$. They are captured using the parenthesis so that you can use them in the query string like$1. In the edited example, only the section after..../rewrite/gets captured;The options between[ ... ]mean that it is theLLast rule to process andQSAthat the original query string is also added to the new url. That means that if your url is/hello-world?some_var=4that thesome_varvariable gets appended to the rewritten url:your_file.php?url=hello-world&some_var=4.
This should be really simple, but I want to be able to use the url as a variable like the php frameworks do.mywebsite.com/hello-worldI want my index.php to see "hello-world" as a variable and I want index.php to load. Is this done through php or do I have to use a htaccess file?Many php frameworks use urls to send a message to the index file... for example...mysite.com/controller/viewHow would I route these myself via php?A little help?
PHP pass url to index.php
I've found an answer.The mistake was trying to get theGETparameters withREQUEST_URI. The right usage should be withQUERY STRINGlike this:RewriteCond %{QUERY_STRING} !(p=.*)$ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]*)/?$ /index.php?p=$1
I'm trying to rewrite allwww.site.com/hello to www.site.com/index.php?p=helloand it works with the following code (in.htaccess):RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]*)/?$ /index.php?p=$1But I want to keep the old links working sowww.site.com/?p=hellowill staywww.site.com/?p=helloI've tried the following code but it won't workRewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(\?p=) RewriteRule ^([^/]*)/?$ /index.php?p=$1
RewriteCond with negative conditions
After some extensive research i found out that it was the server.app from Apple that changed a lot of things. This blog was a life saver for me.http://petercompernolle.com/2012/07/26/fixing-httpdconf-in-osx-mountainlionAnd then several hours later, I figured it out. It's no longer stored at /etc/apache2/httpd.conf. For some reason, Apple has changed something that's worked for a long time, and instead created a whole bunch of files in /Library/Server/Web/Config/apache2/sites. There's a .conf file for anything on port 80, another .conf file for the site I created in Server.app, and a whole bunch of other backups made for every change I made in Server.app.
I have a problem that has caused me a few headaches and I'm hoping maybe someone on here has some light they can share.I was previously running OS X Mountain Lion with no issues at all with slim framework. Since upgrading to OS X Mountain Lion, I've had nothing but trouble since it rewrites your httpd.conf and other settings. One of which seems to be htaccess. I have vhosts setup and some previously working using slim are now broken on any url other than/.So my htaccess file has not changed since upgrading so I'm wondering what the problem is. I'm using the default htaccess as supplied in the slim framework download, I even tried a custom one but to no avail.Visiting/produces the required page. Visiting a different URL does this:Not Found The requested URL /myurl was not found on this server.Any one any tips?mod_rewrite is enabled, and this is what my vhost setup is:<Directory "/Users/chris/Sites/slimphp/"> Allow From All AllowOverride All </Directory> <VirtualHost *:80> ServerName "slim.php" DocumentRoot "/Users/chris/Sites/slimphp" </VirtualHost>
Slim Framework .htaccess / mountain lion osx
You needAllowOverride FileInfoin your virtualhost configuration and for thedirectoryin which the .htaccess file is located, to be able to useAddTypedirective.
I'm having an issue adding a mime type to my server. This is my current .htaccess:AuthUserFile /usr/local/www/pass/.htpasswd AuthType Basic AuthName "Mockups" <LIMIT GET POST> require valid-user </LIMIT>I want to add this:AddType audio/mpeg .mp3But when I do, I get a 500 Internal Server Error. I then reup the .htaccess file without the "AddType" line and it works fine again. What could be the issue?
How to add mime types to an htaccess file?
Have a look at mod_rewrite:http://httpd.apache.org/docs/current/mod/mod_rewrite.htmlYou can, for example, do it like this:RewriteEngine on RewriteRule washington community.php?id=4 [L,QSA] RewriteRule denver community.php?id=5 [L,QSA]This would, of course, lead to a LOT of rewrite rules if you have much cities. So, a IMHO smarter way would be to rewrite the URI slug to community.php and lookup the ID from some sort of database:RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCOnd %{REQUEST_FILENAME} !-d RewriteRule /?([a-z-]+) community.php?city=$1 [L,QSA]HTH
i have a url like this.http://www.somesite.com/community.php?id=4for id number 4 would equal Washington for id number 5 would equal Denver for id number 6 would equal New YorkI would like the url to be rewritten like this.http://www.somesite.com/washington for id = 4 http://www.somesite.com/denver for id = 5is this possible?How would I go about doing it?
PHP URL Rewrite